In the first example the data race condition will be noticed by having the assert fail.
So how is this possible? y > x should always be false, as y
is written after x
and read before x.
Even if you consider all interleaving of
Thread 1 Thread 2
----------------------------------
read y
read x
write x 1
write y 1
you should always have x <= y
But in a safe execution, if read v
during the execution of a write v
, there is no guarantee on the value read.
v is 0
T1 write 1: wwwwwwwww
T2 read : rrrrr
T3 read : rrrrr
In this case the value read by T2 can be anything, like 42
. Meanwhile, the value read by T3 is guaranteed to be 1.
In the first case a
and b
can be anything, so the assertion may fail.
The "fix" offers the guarantee that the data race (concurrent read\write) will never occur, and that a
and b
will always be either 0 or 1.