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

查看:23
本文介绍了使用两个线程在 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 中是有限的.我问这个问题的原因是我在一个大项目中一直在为一个奇怪而罕见的错误苦苦挣扎,直到现在,我能想出解释这个错误的唯一原因是需要同步以上操纵.(由于这个bug非常罕见,所以我很难证明我的猜想是否正确)

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天全站免登陆