Please refer our last post to understand the race condition explanation,
Consider that there are two threads of execution, both enter below critical region, and the initial value of i is 3. The desire
Thread 1 Thread 2
get i (3) —
increment i (3 > 4) —
write back i (4) —
— get i (4)
— increment i (4 > 5)
write back i (5)
As expected, 3 incremented twice is 5. A possible outcome, however, is the following:
Thread 1 Thread 2
get i (3) get i (3)
increment i (3 > 4) —
— increment i (3 > 4)
write back i (4) —
— write back i (4)
If both threads of execution read the initial value of i before it is incremented, both
threads increment and save the same value. As a result, the variable i contains the value
3 when, in fact, it should now contain 4. This is one of the simplest examples of a
critical region.
Thread 1 Thread 2
get i (3) —
increment i (3 > 4) —
write back i (4) —
— get i (4)
— increment i (4 > 5)
write back i (5)
As expected, 3 incremented twice is 5. A possible outcome, however, is the following:
Thread 1 Thread 2
get i (3) get i (3)
increment i (3 > 4) —
— increment i (3 > 4)
write back i (4) —
— write back i (4)
If both threads of execution read the initial value of i before it is incremented, both
threads increment and save the same value. As a result, the variable i contains the value
3 when, in fact, it should now contain 4. This is one of the simplest examples of a
critical region.