Concurrent Programming · Mutual Exclusion

Peterson's Algorithm

An interactive step-by-step visualizer showing how two processes safely share a critical section using flags and a turn variable — with zero hardware support.

flag[i] — Interest

Each process raises its flag to signal "I want to enter the critical section." Like raising your hand in class before speaking.

turn — Courtesy

After flagging, a process politely says "you go first" by setting turn = j. This gift breaks ties and prevents deadlock.

Wait Condition

Wait only when BOTH: other process wants in AND it is the other's turn. If either is false → enter immediately.

Shared Variables
flag[0]
false
P0 wants in?
flag[1]
false
P1 wants in?
turn
0
whose courtesy
violations
0
exclusion breaks
Processes
step 0
Process P0
Idle
    step 0
    Process P1
    Idle
      Event Log
      Controls
      Speed 3x
      How to use:
      Click Step to advance one action at a time. Watch how flags and turn change. Auto-run simulates continuous interleaving.
      waiting...
      Algorithm Guarantees
      🔒

      Mutual Exclusion

      Only one process can be in the critical section at any time. The turn variable ensures this — both can't win the coin flip.

      Progress

      If one process is not interested (flag[j] = false), the other enters immediately without waiting. No unnecessary blocking.

      ⚖️

      Bounded Waiting

      After P0 exits and sets turn = 1, P1 is guaranteed entry on its next attempt. No starvation — each process waits at most one turn.