Short answer: Lamport’s bakery algorithm is an n-thread mutual-exclusion lock built from atomic reads and writes. A thread takes a ticket numbered one more than any ticket it can see, and it waits until every thread that holds a smaller ticket, or an equal ticket and a smaller id, has left. The choosing flag covers the window while the ticket is being selected. The algorithm satisfies mutual exclusion and first-come-first-served order in the ticket numbers. Ticket values grow without bound.
What the problem actually asks
Peterson’s algorithm names two threads. For n threads the tie among arrivals has to be a total order. A ticket number provides it. Because the read of other tickets and the write of one’s own are not one atomic snapshot, two threads can pick the same number. The thread id breaks that tie. The choosing flag stops a third thread from reading a ticket that is still zero while its owner is in the middle of choosing, which would let the newcomer cut in line.
The doorway, the ticket selection, is the first-come-first-served boundary. A thread that has not entered the doorway does not overtake one that has finished it. That fairness is stronger than Peterson’s bounded waiting story and is the reason the bakery is taught.
What the algorithm guarantees
Under sequential consistency, at most one thread is in the critical section, and the ticket order is respected. Time to enter depends on how many threads are ahead. Extra memory is a flag and a ticket per thread. Tickets increase without a reset in the basic algorithm, so a fixed-width integer eventually wraps and the order breaks. A practical system does not use this lock. A queue lock or a futex does. The bakery algorithm is the existence proof that n-thread mutual exclusion and FIFO doorway order are possible with reads and writes.
As with Peterson, real memory models need fences. A plain store to a ticket can be invisible to a spinning thread, or visible out of order with the choosing flag.
The working steps
- Thread i sets choosing[i] = true, then sets ticket[i] to one more than the maximum ticket it reads, then sets choosing[i] = false.
- For every other thread j, wait while choosing[j] is true, then wait while ticket[j] is nonzero and (ticket[j], j) is lexicographically smaller than (ticket[i], i).
- Enter the critical section.
- Set ticket[i] = 0 on exit. A zero ticket means not contending.
- Insert memory barriers so the choosing flag and the ticket write cannot be reordered or cached out of the spinning reads.
FIFO order is about the doorway, not about the wall-clock time of the request if the ticket reads are slow. The algorithm does not bound the ticket width. It is not a reader-writer lock and not a queue lock with local spinning. It is the n-thread read-write solution.
Approaches that look simpler and fail
| Approach | Why it fails when the choosing flag is skipped |
|---|---|
| Take a ticket with no choosing flag | Another thread can observe a stale zero ticket, take a smaller number, and enter first even though it arrived after the doorway started. The flag closes that window. |
| Break equal tickets by a random choice | Both threads can decide they win. The smaller thread id is a total order both sides compute the same way. |
| Wrap a fixed-width ticket and keep comparing numerically | A wrapped small number looks fresher than an old large one. The basic algorithm assumes unbounded tickets. |
| Use the lock on a weakly ordered machine without fences | The spinning thread can see the ticket and the flag in an order the proof forbids. The memory order is part of the implementation. |
Two threads can use Peterson’s algorithm. A production lock uses atomic compare-and-swap or a futex. The bakery algorithm is the n-thread ticket lock from reads and writes.
A working example
This Python fragment gives two threads bakery tickets. The choosing flag covers the window while a ticket is being selected, and the smaller ticket, then the smaller id, enters. One trace takes the tickets in order. Another tries to enter out of order and is rejected. It prints exclusive.
def enter_order(ticket):
# ticket[i] is 0 when thread i is idle
waiting = [i for i in (0, 1) if ticket[i]]
waiting.sort(key=lambda i: (ticket[i], i))
return waiting
def conflicts(schedule):
ticket = [0, 0]
choosing = [False, False]
inside = [False, False]
next_ticket = 1
for who, action in schedule:
if action == "begin":
choosing[who] = True
elif action == "take":
ticket[who] = next_ticket
next_ticket += 1
choosing[who] = False
elif action == "enter":
if choosing[1 - who]:
return True
order = enter_order(ticket)
if not order or order[0] != who:
return True
inside[who] = True
elif action == "leave":
inside[who] = False
ticket[who] = 0
if inside[0] and inside[1]:
return True
return False
trace = [(0, "begin"), (1, "begin"), (0, "take"), (1, "take"), (0, "enter"), (0, "leave"), (1, "enter"), (1, "leave")]
bad = [(0, "begin"), (1, "begin"), (0, "take"), (1, "take"), (0, "enter"), (1, "enter")]
assert conflicts(trace) is False and conflicts(bad) is True
print("exclusive")
Where it is used
Lamport’s bakery algorithm is the proof that n threads can lock with only reads and writes, in ticket order. A production lock is a futex or a compare-and-swap. The Linux ticket spinlock was the deployed relative of the ticket idea, not this bakery code.
When you can drop this algorithm
Drop the bakery algorithm in production code. Use a library mutex. Keep it when the point is an n-thread FIFO mutual exclusion proof, and bound or reclaim the tickets if the process runs long enough to wrap.
Why this stays published
We publish this so a search for the bakery algorithm returns the ticket, the choosing flag, and the lexicographic wait. Lamport’s bakery algorithm gives n threads mutual exclusion and doorway FIFO order by taking a ticket and waiting for every smaller ticket.
本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。
