是否有多个线程可以在连续内存块中写入的最小块大小,以避免竞争条件或值丢失?
例如,32 个线程能否在不影响其他值的情况下写入此数组的各个元素?
int array[32];
这个怎么样?
bool array[32];
将简单的 true/false 存储到位数组中的对象怎么样?
我猜有一些 block 写入大小或缓存相关功能会发挥作用来决定这一点。那是对的吗?关于这个尺寸(平台定义等)有什么标准/安全的吗?
最佳答案
Is there a minimal block size that multiple threads can write to in a contiguous block of memory that avoids race conditions or the losing of values?
没有。仅当两个线程访问同一内存位置(即同一字节)时才会发生冲突(和潜在的数据竞争)。访问不同对象的两个线程不会发生冲突。
For example, can 32 threads write to individual elements of this array without affecting the other values?
是的,每个元素都有自己的内存位置,因此访问不同元素的两个线程不会发生冲突。
How about this?
是的;同样,每个 bool
都有自己的位置。
How about an object that stores simple true/false into a bit array?
没有;这会将多个值打包到一个更大的元素中,并且访问同一个更大元素的两个线程会发生冲突。
I'm guessing there is some block write size or cache related functionality that would come into play that determines this.
当多个线程访问同一缓存行时,可能会影响性能(称为虚假共享);但该语言保证只要它们不访问相同的内存位置,它就不会影响程序的正确性。
关于c++ - 线程安全和 block 写入大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20196252/