Is unprotected access to shared variable always a data race? Is unprotected access to shared variable always a data race? multithreading multithreading

Is unprotected access to shared variable always a data race?


In the C++ standard, a race is defined:

1.10/4: Two expression evaluations conflict if one of them modifies a memory location and the other one accesses or modifies the same memory location.

1.10/21: The execution of a program contains a data race if it contains two conflicting actions in different threads, at least one of which is not atomic, and neither happens before the other. Any such data race results in undefined behavior.

Supposing that you have several threads running the same code, due to the fact that func() would always return 0 (your claim), none of the threads could change the content of x. Furthermore, y is a local variable of a function executed by a thread, so it is not shared. Hence, no race condition could occur in this scenario.

The compiler is not allowed to make the transformations corresponding to the second snippet because:

1.10/22: 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.

But if yourself write the snippet, under the conditions explained above might encounter racing conditions since the x is not atomic, and there could be read access in one thread (temp=x) and write access in the other (either x=0 or in the default section of the other thread (x=temp)