c - 修改数组的一个元素而另一个线程修改同一数组的另一个元素是否是明确定义的行为?

标签 c synchronization pthreads undefined-behavior

给定一个类型为 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/

相关文章:

c - "struct a a1 = {0};"不同于 "struct a a2 = {5};"为什么?

c - 在 C 中传递地址

c - 在 C 中返回数组的数组

javascript - 与express js一起使用的synchronize.js

android - Cloudant 连续复制 Android

c - 段错误(核心转储)错误消息

c - 调用免费电话前是否需要重置保护

Java ConcurrentSkipListMap : adding atomically another Collection object

c - C 中的 Posix Pthread

c - Linux Pthread 库,线程参数