Bakery Algorithm
Lamport's bakery algorithm solves the critical-section problem for any number of processes in software: each process takes a numbered ticket, and the smallest (number, pid) pair goes first.
Take a Number, Wait Your Turn
- Doorway – announce that you are choosing, take ticket 1 + max(all tickets), stop choosing.
- Wait – for every other process, wait until it has finished choosing, then wait while its (number, pid) is smaller than yours.
- Critical section – enter once nobody is ahead of you.
- Exit – set your ticket back to 0.
Lamport's bakery algorithm, published by Leslie Lamport in 1974, is a software solution to the critical-section problem for n processes. It copies the ticket machine at a bakery counter: a customer who arrives takes a number one larger than any number already handed out, and the customer holding the smallest number is served next.
Peterson's solution works for exactly two processes. The bakery algorithm generalises the idea to any number, needs only ordinary reads and writes of shared memory (no special atomic instruction), and even tolerates a read that overlaps a write and returns a garbage value.
- Ticket 0 is reserved for "not interested", which is why every real ticket is at least 1
- Two processes can take the same ticket; the pid breaks the tie, as the section below shows
What a Correct Solution Must Do
- Mutual exclusion – at most one process is in its critical section at any moment.
- Progress – if nobody is inside and some processes want in, one of them gets in; processes in their remainder section have no say.
- Bounded waiting – once a process asks to enter, only a limited number of others can enter ahead of it.
A process runs an entry section before its critical section and an exit section after it; the rest is the remainder section. Any correct solution must satisfy three requirements, covered in depth in race conditions and critical sections. The proof further down shows how this algorithm meets each one.
- Entry section = doorway + waiting loop
- Exit section = number[i] = 0
- Mutual exclusion alone is easy; all three together is the problem
Pseudocode
- choosing[i] = true – I am about to take a ticket.
- number[i] = 1 + max(number[0], …, number[n − 1]) – my ticket.
- choosing[i] = false – my ticket is final.
- for j = 0 to n − 1: while (choosing[j]) wait – let j finish writing its ticket;
- while (number[j] ≠ 0 and (number[j], j) < (number[i], i)) wait – j is ahead of me.
- critical section
- number[i] = 0 – exit section; then the remainder section.
Two shared arrays of size n hold all the state. choosing[i] is true while process i is picking its ticket. number[i] is its ticket; 0 means process i does not want the critical section. Both start false and 0.
Tickets are compared as pairs: (a, i) < (b, j) if a < b, or a == b and i < j. This lexicographic order breaks ties by process id, because two processes that read max(number) at the same moment will compute the same ticket.
- The doorway is steps 1 to 3; everything after is the bakery (waiting) part
- Only process i writes choosing[i] and number[i]; others only read them
- The waiting loop checks every j once, in order, busy-waiting on each
Terms, operations, and practical uses
Core vocabulary
- choosing[i]True while process i is computing its ticket.
- number[i]Process i's ticket; 0 means not interested.
- DoorwayThe ticket-taking part of the entry section.
- Lexicographic order(a, i) < (b, j) if a < b, or a = b and i < j.
- Busy waitingLooping on a condition instead of sleeping.
Mechanisms
- Take a ticketnumber[i] = 1 + max(number).
- Wait for choosingNever read a ticket that is still being written.
- Wait for smaller pairswhile number[j] ≠ 0 and (number[j], j) < (number[i], i).
- Exitnumber[i] = 0.
- BoundOvertaken at most n − 1 times: first come, first served.
Related lessons
- Peterson's SolutionThe two-process software solution that this lesson generalises to n.
- Race Conditions and Critical SectionsThe problem and its three requirements.
- Test-and-Set and SpinlocksHardware-assisted locks that replace software solutions.
- Mutexes, Semaphores and MonitorsBlocking synchronisation without busy waiting.
Three processes, one scripted run
N = 3
# Which process takes its next atomic action at each step.
SCHEDULE = (
[0, 0, 0, 0, 0] # P0: doorway, ticket 1, enters the critical section
+ [1, 1] # P1: choosing, reads max = 1, but has not written its ticket yet
+ [2, 2, 2, 2, 2] # P2: also reads max = 1, writes 2, scans, waits for P0
+ [0] # P0 leaves
+ [2] # P2 waits: P1 is still choosing
+ [1, 1] # P1 writes 2, a tie with P2, and leaves the doorway
+ [2, 1] # P2 loses the tie on pid; P1 enters
+ [0, 0, 0, 0, 0] # P0 comes back: ticket 3, waits for P1
+ [1, 2, 0, 2, 0, 0] # P1 out, P2 in, P0 waits, P2 out, P0 in and out
)
# The same run up to step 16, then P1 scans while P2 is still inside.
BROKEN = SCHEDULE[:16] + [1]
def simulate(schedule, use_choosing=True):
choosing = [False] * N
number = [0] * N
# pc: 0 doorway, 1 read max, 2 write ticket, 3 leave doorway, 4 scan, 5 in CS
pc = [0] * N
seen_max = [0] * N
scan_j = [0] * N
inside = []
log = []
safe = True
for step, i in enumerate(schedule, start=1):
if pc[i] == 0:
choosing[i] = True
msg, pc[i] = f"choosing[{i}] = true", 1
elif pc[i] == 1:
# Reading the array is not atomic with writing the ticket below.
seen_max[i] = max(number)
msg, pc[i] = f"reads max(number) = {seen_max[i]}", 2
elif pc[i] == 2:
number[i] = seen_max[i] + 1
msg, pc[i] = f"number[{i}] = {number[i]}", 3
elif pc[i] == 3:
choosing[i] = False
scan_j[i] = 0
msg, pc[i] = f"choosing[{i}] = false", 4
elif pc[i] == 4:
msg = ""
while scan_j[i] < N:
j = scan_j[i]
if j != i and use_choosing and choosing[j]:
msg = f"waits: P{j} is still choosing"
break
if j != i and number[j] != 0 and (number[j], j) < (number[i], i):
msg = f"waits: ({number[j]}, {j}) < ({number[i]}, {i})"
break
scan_j[i] += 1
if scan_j[i] == N:
inside.append(i)
if len(inside) > 1:
safe = False
msg, pc[i] = "enters critical section", 5
else:
inside.remove(i)
number[i] = 0
msg, pc[i] = f"leaves, number[{i}] = 0", 0
log.append((step, i, msg, number[:], choosing[:], inside[:]))
return log, safe
def row(entry):
step, i, msg, number, choosing, inside = entry
flags = " ".join("T" if c else "." for c in choosing)
nums = " ".join(str(v) for v in number)
cs = " ".join(f"P{p}" for p in inside) or "-"
return f"{step:>2} P{i} {msg:<30} number [{nums}] choosing [{flags}] CS {cs}"
log, safe = simulate(SCHEDULE)
for entry in log:
print(row(entry))
order = [f"P{e[1]}" for e in log if e[2] == "enters critical section"]
print("Critical section order:", " ".join(order))
print("Mutual exclusion held:", "yes" if safe else "no")
print()
print("Same run without waiting on choosing[]:")
log, safe = simulate(BROKEN, use_choosing=False)
for entry in log:
if entry[2] == "enters critical section":
print(row(entry))
print("Mutual exclusion held:", "yes" if safe else "no")#include <algorithm>
#include <cstdio>
#include <string>
#include <utility>
#include <vector>
const int N = 3;
// Which process takes its next atomic action at each step.
const std::vector<int> SCHEDULE = {
0, 0, 0, 0, 0, // P0: doorway, ticket 1, enters the critical section
1, 1, // P1: choosing, reads max = 1, but has not written its ticket yet
2, 2, 2, 2, 2, // P2: also reads max = 1, writes 2, scans, waits for P0
0, // P0 leaves
2, // P2 waits: P1 is still choosing
1, 1, // P1 writes 2, a tie with P2, and leaves the doorway
2, 1, // P2 loses the tie on pid; P1 enters
0, 0, 0, 0, 0, // P0 comes back: ticket 3, waits for P1
1, 2, 0, 2, 0, 0, // P1 out, P2 in, P0 waits, P2 out, P0 in and out
};
struct Entry {
int step, pid;
std::string msg;
std::vector<int> number;
std::vector<bool> choosing;
std::vector<int> inside;
};
std::pair<std::vector<Entry>, bool> simulate(const std::vector<int>& schedule, bool useChoosing = true) {
std::vector<bool> choosing(N, false);
std::vector<int> number(N, 0);
// pc: 0 doorway, 1 read max, 2 write ticket, 3 leave doorway, 4 scan, 5 in CS
std::vector<int> pc(N, 0), seenMax(N, 0), scanJ(N, 0), inside;
std::vector<Entry> log;
bool safe = true;
for (size_t s = 0; s < schedule.size(); s++) {
int i = schedule[s];
std::string msg;
if (pc[i] == 0) {
choosing[i] = true;
msg = "choosing[" + std::to_string(i) + "] = true";
pc[i] = 1;
} else if (pc[i] == 1) {
// Reading the array is not atomic with writing the ticket below.
seenMax[i] = *std::max_element(number.begin(), number.end());
msg = "reads max(number) = " + std::to_string(seenMax[i]);
pc[i] = 2;
} else if (pc[i] == 2) {
number[i] = seenMax[i] + 1;
msg = "number[" + std::to_string(i) + "] = " + std::to_string(number[i]);
pc[i] = 3;
} else if (pc[i] == 3) {
choosing[i] = false;
scanJ[i] = 0;
msg = "choosing[" + std::to_string(i) + "] = false";
pc[i] = 4;
} else if (pc[i] == 4) {
while (scanJ[i] < N) {
int j = scanJ[i];
if (j != i && useChoosing && choosing[j]) {
msg = "waits: P" + std::to_string(j) + " is still choosing";
break;
}
if (j != i && number[j] != 0 && std::make_pair(number[j], j) < std::make_pair(number[i], i)) {
msg = "waits: (" + std::to_string(number[j]) + ", " + std::to_string(j) + ") < (" +
std::to_string(number[i]) + ", " + std::to_string(i) + ")";
break;
}
scanJ[i]++;
}
if (scanJ[i] == N) {
inside.push_back(i);
if (inside.size() > 1) safe = false;
msg = "enters critical section";
pc[i] = 5;
}
} else {
inside.erase(std::find(inside.begin(), inside.end(), i));
number[i] = 0;
msg = "leaves, number[" + std::to_string(i) + "] = 0";
pc[i] = 0;
}
log.push_back({(int)s + 1, i, msg, number, choosing, inside});
}
return {log, safe};
}
void printRow(const Entry& e) {
std::string flags, nums, cs;
for (int k = 0; k < N; k++) {
flags += std::string(k ? " " : "") + (e.choosing[k] ? "T" : ".");
nums += (k ? " " : "") + std::to_string(e.number[k]);
}
for (int p : e.inside) cs += (cs.empty() ? "P" : " P") + std::to_string(p);
if (cs.empty()) cs = "-";
std::printf("%2d P%d %-30s number [%s] choosing [%s] CS %s\n", e.step, e.pid, e.msg.c_str(),
nums.c_str(), flags.c_str(), cs.c_str());
}
int main() {
auto [log, safe] = simulate(SCHEDULE);
std::string order;
for (const Entry& e : log) {
printRow(e);
if (e.msg == "enters critical section") order += (order.empty() ? "P" : " P") + std::to_string(e.pid);
}
std::printf("Critical section order: %s\n", order.c_str());
std::printf("Mutual exclusion held: %s\n", safe ? "yes" : "no");
// The same run up to step 16, then P1 scans while P2 is still inside.
std::vector<int> broken(SCHEDULE.begin(), SCHEDULE.begin() + 16);
broken.push_back(1);
std::printf("\nSame run without waiting on choosing[]:\n");
auto [log2, safe2] = simulate(broken, false);
for (const Entry& e : log2)
if (e.msg == "enters critical section") printRow(e);
std::printf("Mutual exclusion held: %s\n", safe2 ? "yes" : "no");
}import java.util.*;
public class Main {
static final int N = 3;
// Which process takes its next atomic action at each step.
static final int[] SCHEDULE = {
0, 0, 0, 0, 0, // P0: doorway, ticket 1, enters the critical section
1, 1, // P1: choosing, reads max = 1, but has not written its ticket yet
2, 2, 2, 2, 2, // P2: also reads max = 1, writes 2, scans, waits for P0
0, // P0 leaves
2, // P2 waits: P1 is still choosing
1, 1, // P1 writes 2, a tie with P2, and leaves the doorway
2, 1, // P2 loses the tie on pid; P1 enters
0, 0, 0, 0, 0, // P0 comes back: ticket 3, waits for P1
1, 2, 0, 2, 0, 0 // P1 out, P2 in, P0 waits, P2 out, P0 in and out
};
record Entry(int step, int pid, String msg, int[] number, boolean[] choosing, List<Integer> inside) {}
static boolean safe;
static List<Entry> simulate(int[] schedule, boolean useChoosing) {
boolean[] choosing = new boolean[N];
int[] number = new int[N];
// pc: 0 doorway, 1 read max, 2 write ticket, 3 leave doorway, 4 scan, 5 in CS
int[] pc = new int[N], seenMax = new int[N], scanJ = new int[N];
List<Integer> inside = new ArrayList<>();
List<Entry> log = new ArrayList<>();
safe = true;
for (int s = 0; s < schedule.length; s++) {
int i = schedule[s];
String msg = "";
if (pc[i] == 0) {
choosing[i] = true;
msg = "choosing[" + i + "] = true";
pc[i] = 1;
} else if (pc[i] == 1) {
// Reading the array is not atomic with writing the ticket below.
seenMax[i] = Arrays.stream(number).max().getAsInt();
msg = "reads max(number) = " + seenMax[i];
pc[i] = 2;
} else if (pc[i] == 2) {
number[i] = seenMax[i] + 1;
msg = "number[" + i + "] = " + number[i];
pc[i] = 3;
} else if (pc[i] == 3) {
choosing[i] = false;
scanJ[i] = 0;
msg = "choosing[" + i + "] = false";
pc[i] = 4;
} else if (pc[i] == 4) {
while (scanJ[i] < N) {
int j = scanJ[i];
if (j != i && useChoosing && choosing[j]) {
msg = "waits: P" + j + " is still choosing";
break;
}
boolean ahead = number[j] < number[i] || (number[j] == number[i] && j < i);
if (j != i && number[j] != 0 && ahead) {
msg = "waits: (" + number[j] + ", " + j + ") < (" + number[i] + ", " + i + ")";
break;
}
scanJ[i]++;
}
if (scanJ[i] == N) {
inside.add(i);
if (inside.size() > 1) safe = false;
msg = "enters critical section";
pc[i] = 5;
}
} else {
inside.remove(Integer.valueOf(i));
number[i] = 0;
msg = "leaves, number[" + i + "] = 0";
pc[i] = 0;
}
log.add(new Entry(s + 1, i, msg, number.clone(), choosing.clone(), new ArrayList<>(inside)));
}
return log;
}
static void printRow(Entry e) {
StringJoiner flags = new StringJoiner(" "), nums = new StringJoiner(" "), cs = new StringJoiner(" ");
for (int k = 0; k < N; k++) {
flags.add(e.choosing()[k] ? "T" : ".");
nums.add(String.valueOf(e.number()[k]));
}
for (int p : e.inside()) cs.add("P" + p);
String inside = e.inside().isEmpty() ? "-" : cs.toString();
System.out.printf("%2d P%d %-30s number [%s] choosing [%s] CS %s%n",
e.step(), e.pid(), e.msg(), nums, flags, inside);
}
public static void main(String[] args) {
List<Entry> log = simulate(SCHEDULE, true);
StringJoiner order = new StringJoiner(" ");
for (Entry e : log) {
printRow(e);
if (e.msg().equals("enters critical section")) order.add("P" + e.pid());
}
System.out.println("Critical section order: " + order);
System.out.println("Mutual exclusion held: " + (safe ? "yes" : "no"));
// The same run up to step 16, then P1 scans while P2 is still inside.
int[] broken = Arrays.copyOf(SCHEDULE, 17);
broken[16] = 1;
System.out.println();
System.out.println("Same run without waiting on choosing[]:");
for (Entry e : simulate(broken, false))
if (e.msg().equals("enters critical section")) printRow(e);
System.out.println("Mutual exclusion held: " + (safe ? "yes" : "no"));
}
}Step through it
Running on 3 processes; P1 and P2 read max = 1 before either writes
A Tie Between Two Processes
The tracer follows three processes through a full schedule. The smallest case that needs the tie rule has only two. P0 and P1 both set choosing to true and both read max(number) = 0 before either writes. Each computes 0 + 1, so number = [1, 1].
Both leave the doorway and scan. P0 compares itself with P1: (1, 1) < (1, 0) is false, so P1 is not ahead and P0 enters. P1 compares with P0: (1, 0) < (1, 1) is true, so P1 waits. When P0 writes number[0] = 0 on exit, P1's loop ends and P1 enters. Equal numbers never cause a deadlock or a double entry, because the pid makes every pair different.
- Without the pid, both would see an equal ticket, not a smaller one, and enter together
- If P0 comes back while P1 is inside, it reads max = 1 and takes ticket 2, behind P1
Why It Is Correct
Why choosing[] is needed. In the tracer's schedule, suppose P2 skipped the wait at step 14, while P1 was still choosing. It would read number[1] = 0, treat P1 as uninterested, and enter. P1 would then write ticket 2, compare (2, 2) < (2, 1), find it false, and enter too: two processes inside. The listing reruns the schedule without the choosing wait and prints exactly this violation.
Mutual exclusion. Suppose i is in its critical section and k ≠ i is waiting with a ticket. When i checked k, it first waited until choosing[k] was false. If k had already finished choosing, number[k] was final and i passed only because (number[i], i) < (number[k], k). If k had not yet entered the doorway, k's ticket will be at least number[i] + 1. Either way i's pair is smaller, so k's loop on j = i keeps k waiting while i is inside.
Progress and bounded waiting. The pairs are distinct and totally ordered, so among waiting processes the smallest pair never waits for anyone: no deadlock. Tickets are handed out in order of arrival through the doorway, so the algorithm is first come, first served: a process can be overtaken only by processes that finished their doorway before it did, at most n − 1 of them.
- Crashes: Lamport allowed a failed process to reset its choosing and number to 0, after which it blocks no one; a process that halts while still holding a ticket blocks everyone behind it
Bakery Algorithm vs Peterson's Solution
Both are classic software-only answers to the critical-section problem, both busy-wait, and both assume memory operations happen in program order.
| Aspect | Peterson's solution | Bakery algorithm |
|---|---|---|
| Processes | exactly 2 | any n |
| Shared state | flag[2], turn | choosing[n], number[n] |
| Tie breaking | turn variable | (number, pid) order |
| Waiting order | alternates, bound of 1 | first come, first served, bound n − 1 |
| Entry cost | O(1) | O(n): max over n tickets, then n checks |
| Variable size | bounded | unbounded: tickets can grow without limit |
| Needs atomic reads/writes | yes | no: survives a read overlapping a write |
- Two processes: Peterson is simpler and cheaper
- n processes: this algorithm, or hardware locks such as test-and-set spinlocks
- Neither is used directly in real kernels
Limits and Where the Idea Lives On
Busy waiting. A waiting process spins in its loop, burning CPU time. Real systems prefer locks that put the waiter to sleep, such as mutexes and semaphores.
Unbounded numbers. If the bakery is never empty, every newcomer takes max + 1 and tickets grow forever; a fixed-width integer eventually overflows. Bounded variants exist but are more complex.
Memory ordering. Modern CPUs and compilers reorder loads and stores. Without memory barriers (fences) or sequentially consistent atomics, a process can see number[j] before choosing[j] and the proof no longer holds. O(n) cost per entry also makes it slow for many processes.
- Teaching and exams: the standard n-process software solution, with a clean proof
- Distributed mutual exclusion: Lamport's timestamp-ordered algorithms use the same take-a-number idea across machines
- Hardware without atomic instructions: only plain reads and writes of shared memory are needed
- Ticket locks: real ticket spinlocks keep the first-come order but use one atomic fetch-and-add counter instead