Winter Semester 2026–27 · VIT-AP · BACSE106 · Operating Systems · Dr. Krithika L.B

Session 3.2: Race conditions, the critical-section problem, Peterson's solution and the Bakery algorithm

Why counter++ is unsafe, what any solution to the critical-section problem must guarantee, and two classic software solutions — Peterson for two processes and the Bakery algorithm for n.

Module 3 2 hours Theory CO3
← Before
3.1 IPC
Shared memory, messages
You are here
3.2 Race conditions, the critical-section problem, Peterson's solution and the Bakery algorithm
Module 3 · Process Synchronization
Next →
3.3 Hardware & mutex
TAS, Swap, mutex locks

Learning objectives

By the end of this session you should be able to:

  • Show with an instruction-level trace how a race condition corrupts shared data.
  • Define the critical-section problem and its three requirements.
  • Explain why strict alternation and flag-only attempts fail.
  • Trace Peterson's solution and argue that it satisfies mutual exclusion, progress and bounded waiting.
  • Trace the Bakery algorithm for n processes, including tie-breaking.

Lecture notes

1. Race conditions

Return to the producer–consumer buffer of Session 3.1, now with a shared count of items. The producer executes count++ and the consumer count--. Each looks like one statement, but in machine code each is three instructions — load, modify, store — and a context switch can happen between any two.

Race condition — counter++ and counter-- interleaved (counter starts at 5)Step through the interleaving one instruction at a time.
Race condition

A situation where several processes access and manipulate the same data concurrently and the outcome depends on the particular order in which the accesses take place. To prevent it, only one process at a time may manipulate the shared data — the processes must be synchronized.

2. The critical-section problem

Each of n processes has a segment of code — its critical section — in which it accesses shared data. The problem is to design a protocol so that no two processes are in their critical sections at the same time.

General structure of a process
do {
    entry section          /* ask permission      */
        critical section   /* touch shared data   */
    exit section           /* announce you left   */
        remainder section  /* everything else     */
} while (true);
1 · Mutual exclusion

If a process is in its critical section, no other process can be in its critical section.

2 · Progress

If no process is in its CS and some want to enter, only those not in their remainder sections take part in the decision, and it cannot be postponed forever.

3 · Bounded waiting

There is a limit on how many times others may enter their CS after a process has asked to enter and before it is allowed in (no starvation).

Assume each process runs at non-zero speed, but make no assumption about relative speeds or the number of CPUs.

3. Two failed attempts (why the problem is hard)

Attempt 1 — strict alternation with turn
while (turn != i) ;
  /* CS */
turn = j;

Mutual exclusion ✔. Progress ✘: if P1 is in its remainder section and P0 wants to enter twice in a row, P0 waits for P1 to take its turn.

Attempt 2 — flag only
flag[i] = true;
while (flag[j]) ;
  /* CS */
flag[i] = false;

Mutual exclusion ✔. Progress ✘: if both set their flags at the same time, both wait forever (a livelock/deadlock).

4. Peterson's solution (two processes)

Peterson (1981) combines both ideas: flag[i] says “I want to enter”, and turn says “whose turn it is if we both want to”.

Peterson's solution for process Pi (j = 1 − i)
int turn;
bool flag[2] = {false, false};

do {
    flag[i] = true;                 /* I want to enter            */
    turn = j;                       /* but you may go first       */
    while (flag[j] && turn == j)
        ;                           /* busy wait                  */

        /* critical section */

    flag[i] = false;                /* I am out                   */

        /* remainder section */
} while (true);
Peterson's solution — both processes try to enter at onceStep through the interleaving one instruction at a time.
Why it satisfies all three requirements
  • Mutual exclusion: if both were inside, both flags are true, so each passed its loop because turn equalled its own index — impossible, turn has one value.
  • Progress: a process waits only if the other wants in and it is the other's turn; if the other is in its remainder, its flag is false.
  • Bounded waiting: on leaving, Pj sets its flag false; if it immediately wants back in it sets turn = i, so Pi enters after at most one entry by Pj.
Peterson on modern hardware

Modern CPUs and compilers may reorder independent reads and writes, which can break Peterson's solution. It is taught because it shows the reasoning clearly; real systems use hardware instructions (Session 3.3) or memory barriers.

5. The Bakery algorithm (n processes)

Lamport's Bakery algorithm generalises to n processes, inspired by a bakery where each customer takes a numbered token and the smallest number is served next. Two processes may draw the same number, so ties are broken by process ID: compare pairs (number, id) lexicographically.

Bakery algorithm for process Pi
bool choosing[n];   /* all false */
int  number[n];     /* all 0     */

do {
    choosing[i] = true;
    number[i] = 1 + max(number[0], ..., number[n-1]);   /* take a token  */
    choosing[i] = false;

    for (j = 0; j < n; j++) {
        while (choosing[j])
            ;                                           /* wait while j picks */
        while (number[j] != 0 &&
               (number[j] < number[i] ||
                (number[j] == number[i] && j < i)))
            ;                                           /* j goes first      */
    }

        /* critical section */

    number[i] = 0;                                      /* return the token  */

        /* remainder section */
} while (true);

P1, P2 and P3 want to enter. P1 takes 1; P2 and P3 compute max + 1 at the same moment and both take 2.

P1: 1P2: 2P3: 2

Pairs are compared as (number, id): (1,1) < (2,2) < (2,3). So the order is P1, then P2, then P3.

P1 finds no smaller pair and enters. P2 and P3 spin on P1's number.

P1 exits and sets number[1] = 0. P2 now has the smallest pair and enters; P3 waits because (2,2) < (2,3).

P2 exits; P3 enters. Every process is served in FCFS order of tokens → bounded waiting.

Why choosing? Without it, Pi might compare against Pj's number while Pj is still computing it (reading 0) and wrongly enter at the same time.

VideoBytes

Race conditions and the critical-section problem

Video coming soon

Race conditions and the critical-section problem

Recorded by Dr. Krithika L.B. Slot m3-race

Peterson's solution and the Bakery algorithm

Video coming soon

Peterson's solution and the Bakery algorithm

Recorded by Dr. Krithika L.B. Slot m3-peterson-bakery

Interactive lessons

Work through these in order after the lecture — each one expands a part of the notes with diagrams, hover notes and a quick check.

Lab connection

Check your understanding

Answer each question in your own words first, then reveal the model answer.

Revealed 0
Why is count++ not atomic?

It compiles to load, add, store. A context switch between them lets another process read or write the stale value.

Which requirement does strict alternation violate?

Progress: a process may be blocked from entering even though the other is not in or trying to enter its CS.

In Peterson's solution, what happens if both processes set turn almost simultaneously?

Only the last write survives; the process that wrote last waits and the other enters — mutual exclusion is preserved.

In the Bakery algorithm, P2 and P5 both hold number 4. Who enters first?

P2, because (4, 2) < (4, 5).

Do Peterson and Bakery use busy waiting?

Yes — waiting processes spin in a loop, wasting CPU cycles.

Key takeaways

  • A race condition occurs when the result depends on the interleaving of accesses to shared data.
  • Any CS solution must give mutual exclusion, progress and bounded waiting.
  • Peterson (flag + turn) solves it for two processes; Bakery (tokens + id) for n — both in pure software, both with busy waiting.

Where this leads

Software solutions are subtle and can be broken by modern hardware reordering. Real systems rely on atomic hardware instructions and the locks built on them.

Continue to 3.3 — Hardware synchronization and mutex locks →