Process synchronization and race conditions
Watch a race happen, instruction by instruction.
Operating Systems: Process Synchronization
1. The Problem: What is a Race Condition?
In a multi-tasking operating system, multiple concurrent processes or threads often share data (e.g., shared memory variables, files, or database records). A Race Condition occurs when multiple processes access and manipulate the same shared data concurrently, and the outcome of the execution depends on the specific order in which instructions are executed.
Suppose Process A and Process B both execute
counter++ on a shared variable initialized to 5.
- At machine code level,
counter++expands to three instructions: 1. Read counter, 2. Increment register, 3. Write counter. - If CPU interrupts Process A midway and switches to Process B, the final value of
countercould end up as5or6instead of the correct value7.
2. Anatomy of a Synchronized Process
To prevent race conditions, access to shared data must be synchronized. Each process must request permission to enter its Critical Section. The general code structure for any typical process Pi executing in a loop is defined as follows:
// General structure of a typical process Pi do { entry section critical section exit section remainder section} while (true);
3. Three Requirements for a Valid Critical Section Solution
Any software or hardware protocol designed to solve the Critical Section problem must satisfy three criteria:
- Mutual Exclusion: If process Pi is executing in its critical section, then no other processes can be executing in their critical sections.
- Progress: If no process is executing in its critical section and some processes wish to enter, only those processes not executing in their remainder section can participate in deciding which will enter next.
- Bounded Waiting: There must be a bound or limit on the number of times that other processes are allowed to enter their critical sections after a process has made a request to enter and before that request is granted.
4. Interactive Lab: Race Condition vs. Mutual Exclusion
Use the simulator below to compare unsynchronized execution (Race Condition) with synchronized mutual exclusion locks.