Peterson's solution in Operating Systems - Time & Space Complexity
We want to understand how the time it takes for Peterson's solution to work changes as more attempts to enter the critical section happen.
Specifically, how does waiting time grow when two processes try to access shared resources?
Analyze the time complexity of the following Peterson's solution code snippet for two processes.
// Shared variables
boolean flag[2] = {false, false};
int turn;
// Process i wants to enter critical section
flag[i] = true;
turn = j;
while (flag[j] && turn == j) {
// busy wait
}
// critical section
flag[i] = false;
This code lets two processes take turns safely to enter a critical section without conflicts.
Look at what repeats while waiting.
- Primary operation: The while loop that keeps checking if the other process is ready and whose turn it is.
- How many times: It repeats until the other process leaves the critical section or it's this process's turn.
The waiting time depends on how long the other process stays in the critical section.
| Input Size (n) | Approx. Operations |
|---|---|
| 1 (one attempt) | Few checks, almost no waiting |
| 10 (multiple attempts) | Waiting grows roughly linearly with how long the other process holds the resource |
| 100 (many attempts) | Waiting time increases but only for the process that arrives second each time |
Pattern observation: Waiting grows with how long the other process uses the critical section, but only one process waits at a time.
Time Complexity: O(n)
This means the waiting time grows linearly with the number of times the other process uses the critical section before this process can enter.
[X] Wrong: "Both processes wait at the same time, so waiting doubles."
[OK] Correct: Only one process waits while the other is in the critical section, so waiting is not doubled but linear for the waiting process.
Understanding how Peterson's solution manages waiting helps you explain synchronization and fairness in concurrent programming clearly and confidently.
"What if we added more than two processes? How would the time complexity of waiting change?"