Why does code mutating a shared variable across threads apparently NOT suffer from a race condition?
foo()
is so short that each thread probably finishes before the next one even gets spawned. If you add a sleep for a random time in foo()
before the u++
, you may start seeing what you expect.
It is important to understand a race condition does not guarantee the code will run incorrectly, merely that it could do anything, as it is an undefined behavior. Including running as expected.
Particularly on X86 and AMD64 machines race conditions in some cases rarely cause issues as many of the instructions are atomic and the coherency guarantees are very high. These guarantees are somewhat reduced on multi processor systems where the lock prefix is needed for many instructions to be atomic.
If on your machine increment is an atomic op, this will likely run correctly even though according to the language standard it is Undefined Behavior.
Specifically I expect in this case the code may be being compiled to an atomic Fetch and Add instruction (ADD or XADD in X86 assembly) which is indeed atomic in single processor systems, however on multiprocessor systems this is not guaranteed to be atomic and a lock would be required to make it so. If you are running on a multiprocessor system there will be a window where threads could interfere and produce incorrect results.
Specifically I compiled your code to assembly using https://godbolt.org/ and foo()
compiles to:
foo():
add DWORD PTR u[rip], 1
ret
This means it is solely performing an add instruction which for a single processor will be atomic (though as mentioned above not so for a multi processor system).
I think it is not so much the thing if you put a sleep before or after the u++
. It is rather that operation u++
translates to code that is - compared to the overhead of spawning threads that call foo
- very quickly performed such that it is unlikely to get intercepted. However, if you "prolong" the operation u++
, then the race condition will become much more likely:
void foo()
{
unsigned i = u;
for (int s=0;s<10000;s++);
u = i+1;
}
result: 694
BTW: I also tried
if (u % 2) {
u += 2;
} else {
u -= 1;
}
and it gave me most times 1997
, but sometimes 1995
.