Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it well-defined behavior to modify one element of an array while another thread modifies another element of the same array?

Given an array of type foo_t[n] and a set of n threads, where each of the n threads reads and modifies a different element of the array, do I need to explicitly synchronize modifications of the array or can I assume that concurrently modifying members of the array is well-defined behavior? Does it matter how large foo_t is / what alignment it has?

like image 502
fuz Avatar asked Jun 21 '14 23:06

fuz


1 Answers

What I try to do is well-defined behavior.

See 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.

Note that this language was introduced with C11 to make optimizations that cause bugs like this illegal. Pre-C11 compilers may not abide to this rule.

like image 144
fuz Avatar answered Nov 15 '22 10:11

fuz