The race condition is an undesirable situation that may occur inside a critical section that is when common variables or resources are shared among processes or threads and
- The outcome of execution depends upon the order of execution and
- Processes or threads competes(races) with each other to access the shared variables or resources in CS.
- It leads to data loss or inconsistencies.
Race condition is avoided if the Critical section is atomic that is only one process or a thread can execute in its critical section.
do { Entry Section Critical section Exit Section Remainder Section }while(True)
Data Loss and Inconsistencies:
Example:
Consider a scenario where more then one process are allowed to enter the critical section that is allowed to access the shared variables or resources.
- If one process reads a shared variable and modifies its value(in register-R1) but before the value is written, the other process reads the same variable.
- Hence later process does not read the updated data and modifies the same and also writes it to memory.
- Now the first process again reads the value from its register(R1) and writes its to memory and hence the value of the shared variable updated by the second process is lost. Thus data is either lost or the value is inconsistent if the synchronization is not maintained among processes.
P1 p2 { { x++; x--; } } Internally p1 p2 { { a) Move x to R1 a) Move x to R2 b) Increment the R1 b) Decrement the R2 c) Copy R1 to x c) Copy R2 to x } }
Now as per to above example, consider the value of x to be 5
case 1:
Order : p1(a) -> p1(b)->p2(a)->p2(b)->p2(c)->p1(c)
Value : 6
case 2:
Order : p1(a)->p1(b)->p1(c)->p2(a)->p2(b)->p2(c)
Value : 5
case 3:
Order: p2(a)->p2(b)->p2(c)->p1(a)->p1(b)->p1(c)
value: 5
Hence we can see that the value of x is inconsistent and it depends upon the order of execution. To overcome this both the process must be synchronized.
Race Conditions can be avoided by:
- Mutex
- Semaphore
Diag-1: Race Condition

Relevant Posts:
- Thread Synchronization
- Critical Section
- Mutual Exclusion(Mutex)
- Semaphore
- Mutex Vs Semaphore
- Spin Lock
- Spin Lock Vs Mutex
- Condition Variables
Categories: Operating system (OS)
Leave a Reply