{"id":212,"date":"2026-11-13T12:34:43","date_gmt":"2026-11-13T04:34:43","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-lamports-bakery-algorithm-takes-a-ticket\/"},"modified":"2026-11-13T21:52:54","modified_gmt":"2026-11-13T13:52:54","slug":"how-lamports-bakery-algorithm-takes-a-ticket","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-lamports-bakery-algorithm-takes-a-ticket\/","title":{"rendered":"How Lamport&#8217;s bakery algorithm takes a ticket"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> <strong>Lamport&#8217;s bakery algorithm<\/strong> 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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the problem actually asks<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Peterson&#8217;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&#8217;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.<\/p>\n\n\n<p class=\"wp-block-paragraph\">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&#8217;s bounded waiting story and is the reason the bakery is taught.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the algorithm guarantees<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>The working steps<\/strong><\/h4>\n\n<ol class=\"wp-block-list\">\n<li>Thread i sets choosing[i] = true, then sets ticket[i] to one more than the maximum ticket it reads, then sets choosing[i] = false.<\/li>\n<li>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).<\/li>\n<li>Enter the critical section.<\/li>\n<li>Set ticket[i] = 0 on exit. A zero ticket means not contending.<\/li>\n<li>Insert memory barriers so the choosing flag and the ticket write cannot be reordered or cached out of the spinning reads.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Approaches that look simpler and fail<\/strong><\/h4>\n\n<figure class=\"wp-block-table\">\n<table>\n<thead>\n<tr>\n<th>Approach<\/th>\n<th>Why it fails when the choosing flag is skipped<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Take a ticket with no choosing flag<\/td>\n<td>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.<\/td>\n<\/tr>\n<tr>\n<td>Break equal tickets by a random choice<\/td>\n<td>Both threads can decide they win. The smaller thread id is a total order both sides compute the same way.<\/td>\n<\/tr>\n<tr>\n<td>Wrap a fixed-width ticket and keep comparing numerically<\/td>\n<td>A wrapped small number looks fresher than an old large one. The basic algorithm assumes unbounded tickets.<\/td>\n<\/tr>\n<tr>\n<td>Use the lock on a weakly ordered machine without fences<\/td>\n<td>The spinning thread can see the ticket and the flag in an order the proof forbids. The memory order is part of the implementation.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">Two threads can use Peterson&#8217;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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>A working example<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">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 <code>exclusive<\/code>.<\/p>\n\n<pre><code class=\"language-python\">def enter_order(ticket):\n    # ticket[i] is 0 when thread i is idle\n    waiting = [i for i in (0, 1) if ticket[i]]\n    waiting.sort(key=lambda i: (ticket[i], i))\n    return waiting\n\ndef conflicts(schedule):\n    ticket = [0, 0]\n    choosing = [False, False]\n    inside = [False, False]\n    next_ticket = 1\n    for who, action in schedule:\n        if action == &quot;begin&quot;:\n            choosing[who] = True\n        elif action == &quot;take&quot;:\n            ticket[who] = next_ticket\n            next_ticket += 1\n            choosing[who] = False\n        elif action == &quot;enter&quot;:\n            if choosing[1 - who]:\n                return True\n            order = enter_order(ticket)\n            if not order or order[0] != who:\n                return True\n            inside[who] = True\n        elif action == &quot;leave&quot;:\n            inside[who] = False\n            ticket[who] = 0\n        if inside[0] and inside[1]:\n            return True\n    return False\n\ntrace = [(0, &quot;begin&quot;), (1, &quot;begin&quot;), (0, &quot;take&quot;), (1, &quot;take&quot;), (0, &quot;enter&quot;), (0, &quot;leave&quot;), (1, &quot;enter&quot;), (1, &quot;leave&quot;)]\nbad = [(0, &quot;begin&quot;), (1, &quot;begin&quot;), (0, &quot;take&quot;), (1, &quot;take&quot;), (0, &quot;enter&quot;), (1, &quot;enter&quot;)]\nassert conflicts(trace) is False and conflicts(bad) is True\nprint(&quot;exclusive&quot;)\n<\/code><\/pre>\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Where it is used<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Lamport&#8217;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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>When you can drop this algorithm<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Why this stays published<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">We publish this so a search for the bakery algorithm returns the ticket, the choosing flag, and the lexicographic wait. <strong>Lamport&#8217;s bakery algorithm gives n threads mutual exclusion and doorway FIFO order by taking a ticket and waiting for every smaller ticket.<\/strong><\/p>\n\n\n<p class=\"wp-block-paragraph\">\u672c\u6587\u7531 HoHo \u8207 AI \u5354\u4f5c\u6574\u7406\uff0c\u6700\u5f8c\u66f4\u65b0\u65bc 2026 \u5e74 11 \u6708 13 \u65e5\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Short answer: Lamport&#8217;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,&hellip;<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[30,57],"tags":[],"class_list":["post-212","post","type-post","status-publish","format-standard","hentry","category-algorithms","category-synchronization"],"_links":{"self":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/212","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/comments?post=212"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/212\/revisions"}],"predecessor-version":[{"id":611,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/212\/revisions\/611"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=212"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=212"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=212"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}