给定一个类型为 foo_t[n]
的数组和一组 n 个线程,其中每个 n 线程读取和修改一个数组的不同元素,我是否需要显式同步数组的修改,或者我是否可以假设同时修改数组的成员是明确定义的行为? foo_t
有多大/它的对齐方式有关系吗?
最佳答案
我尝试做的是明确定义的行为。
参见 ISO/IEC 9899:2011 §5.1.2.4.27:
NOTE 13 Compiler transformations that introduce assignments to a potentially shared memory location that would not be modified by the abstract machine are generally precluded by this standard, since such an assignment might overwrite another assignment by a different thread in cases in which an abstract machine execution would not have encountered a data race. This includes implementations of data member assignment that overwrite adjacent members in separate memory locations. We also generally preclude reordering of atomic loads in cases in which the atomics in question may alias, since this may violate the "visible sequence" rules.
请注意,此语言是随 C11 引入的,用于进行导致错误的优化 like this非法的。 C11 之前的编译器可能不遵守此规则。
关于c - 修改数组的一个元素而另一个线程修改同一数组的另一个元素是否是明确定义的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24346765/