Race Conditions - aryanjoshi0823/5143-Operating-System GitHub Wiki

A race condition in an operating system occurs when the behavior of a system depends on the sequence or timing of uncontrollable events, such as the scheduling of threads or processes. In such cases, multiple processes or threads access shared resources simultaneously, leading to unpredictable results and potential data corruption.


Example of a Race Condition

Consider two threads incrementing a shared variable x initialized to 0.

Code Example:

int x = 0;

Thread 1: x = x + 1;
Thread 2: x = x + 1;

Possible Execution:

  1. Thread 1 reads x (value = 0).
  2. Thread 2 reads x (value = 0).
  3. Thread 1 increments x to 1 and writes back.
  4. Thread 2 increments x to 1 and writes back.

Final Value of x:
Instead of 2, the value of x is 1 due to the race condition.


Common Scenarios Leading to Race Conditions

  1. Concurrent File Access:
    Two processes read and write to the same file without proper locking mechanisms.

  2. Shared Memory:
    Multiple threads updating a global variable simultaneously.

  3. Inter-process Communication (IPC):
    Processes communicate through shared resources like message queues or semaphores without synchronization.

  4. I/O Operations:
    Multiple processes accessing a shared printer or disk simultaneously.


Real-Life Analogy

Imagine a ticket counter at a railway station where multiple people are trying to book tickets simultaneously. If there is no proper queue (synchronization), multiple people may end up booking the same ticket due to a race condition.