当使用两个线程在C/C ++中操作不同的数组索引时,是否需要同步? [英] When manipulating different array indices in C/C++ with two threads, is synchronization needed?

查看:75
本文介绍了当使用两个线程在C/C ++中操作不同的数组索引时,是否需要同步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个定义如下的数组:

Suppose I have an array defined as follows:

volatile char v[2];

我有两个线程(分别由A,B表示)操纵数组v.如果我确保A,B随时使用不同的索引,也就是说,如果A现在正在操纵v[i],那么B要么什么都不做,要么在操纵v[1-i].我想知道这种情况是否需要同步吗?

And I have two threads (denoted by A, B respectively) manipulating array v. If I ensure that A, B use different indices at any time, that is to say, if A is now manipulating v[i], then B is either doing nothing, or manipulating v[1-i]. I wonder is synchronization needed for this situation?

我已经提到这个问题,但是我认为这在Java中是有限的.我之所以问这个问题,是因为我已经在大型项目中挣扎了几天之久,而直到现在,我一直在努力解决这个奇怪的罕见错误,而我想出唯一的理由来解释该错误的原因是:以上操纵. (由于该错误非常罕见,因此我很难证明我的猜想是否正确)

I have referred to this question, however I think it is limited in Java. The reason why I ask this question is that I have been struggling with a strange and rare bug in a large project for days, and up to now, the only reason I could come up with to explain the bug is that synchronization is needed for the above manipulation. (Since the bug is very rare, it is hard for me to prove whether my conjecture is true)

v可以读取和修改.

推荐答案

可能是编译器错误或硬件限制.

It might be a compiler bug or a hardware limitation.

有时,当从内存访问少于32位/64位变量时,处理器将读取32位,设置适当的8位或16位,然后写回整个寄存器.这意味着它将同时读取/写入相邻的内存,从而导致数据争用.

Sometimes, when a less than 32-bit/64-bit variable is accesses from memory, the processor will read 32 bits, set the apprpriate 8 or 16 bits, then write back the whole register. That means it will read/write the adjacent memory as well, leading to a data race.

解决方案是

  • 使用字节访问指令.它们可能不适用于您的处理器,或者您的编译器不知道如何使用它们.

  • use byte-access instructions. They may not be available for your processor or your compiler does not know to use them.

填充您的元素以避免这种共享.如果目标平台不支持字节访问,则编译器应自动执行此操作.但是在一个数组中,这与内存布局要求冲突.

pad your elements to avoid this kind of sharing. The compiler should do it automatically if your target platform does not support byte access. But in an array, this conflicts with the memory layout reqiurements.

C ++ 03/C ++ 11辩论

在经典C ++中,您有责任避免/减轻这种行为.如其他答案所述,在C ++ 11中这违反了内存模型的要求.

In classic C++ it's up to you to avoid/mitigate this kind of behaviour. In C++11 this violates memry model requitements, as stated in other answers.

这篇关于当使用两个线程在C/C ++中操作不同的数组索引时,是否需要同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆