ArticleslgStudy

computer science

Lamport's bakery algorithm

Lamport's bakery algorithm is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Lamport's bakery algorithm rather than just read about it. In short: Lamport's bakery algorithm is a computer algorithm devised by computer scientist Leslie Lamport, as part of his long study of the formal correctness of concurrent systems, which is intended to improve the safety in the usage of shared resources among multiple threads by means of mutual exclusion. In computer science, it is common for multiple threads to simultaneously access the same resources.

Key takeaways

  • Lamport's bakery algorithm belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Lamport's bakery algorithm to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Lamport's bakery algorithm from memory before moving on to harder problems.

Reference excerpt

Lamport's bakery algorithm is a computer algorithm devised by computer scientist Leslie Lamport, as part of his long study of the formal correctness of concurrent systems, which is intended to improve the safety in the usage of shared resources among multiple threads by means of mutual exclusion. In computer science, it is common for multiple threads to simultaneously access the same resources. Data corruption can occur if two or more threads try to write into the same memory location, or if one thread reads a memory location before another has finished writing into it. Lamport's bakery algorithm is one of many mutual exclusion algorithms designed to prevent concurrent threads entering critical sections of code concurrently to eliminate the risk of data corruption.

Algorithm

Analogy Lamport envisioned a bakery with a numbering machine at its entrance so each customer is given a unique number. Numbers increase by one as customers enter the store. A global counter displays the number of the customer that is currently being served. All other customers must wait in a queue until the baker finishes serving the current customer and the next number is displayed. When the customer is done shopping and has disposed of their number, the clerk increments the number, allowing the next customer to be served. That customer must draw another number from the numbering machine in order to shop again. According to the analogy, the "customers" are threads, identified by the letter i, obtained from a global variable. It is possible that more than one thread will get the same number n when they request it; this cannot be avoided (without first solving the mutual exclusion problem, which is the goal of the algorithm). Therefore, it is assumed that the thread identifier i is also a priority. A lower value of i means a higher priority and threads with higher priority will enter the critical section first. This is the equivalent of giving the number ticket to the oldest customer to request it.

Critical section The critical section is that part of code that requires exclusive access to resources and may only be executed by one thread at a time. In the bakery analogy, it is when the customer trades with the baker that others must wait. When a thread wants to enter the critical section, it has to check whether now is its turn to do so. It should check the number n of every other thread to make sure that it has the smallest one. In case another thread has the same number, the thread with the smallest i will enter the critical section first. In pseudocode this comparison between threads a and b can be written in the form:

// Let na - the customer number for thread a, and // ia - the thread number for thread a, then

(na, ia) < (nb, ib)

which is equivalent to:

(na < nb) or ((na == nb) and (ia < ib))

Once the thread ends its critical job, it gets rid of its number and enters the non-critical section.

Non-critical section The non-critical section is the part of code that doesn't need exclusive access. It represents some thread-specific computation that doesn't interfere with other threads' resources and execution. This part is analogous to actions that occur after shopping, such as putting change back into the wallet.

Implementation of the algorithm

Definitions In Lamport's original paper, the entering variable is known as choosing, and the following conditions apply:

Words choosing [i] and number [i] are in the memory of process i, and are initially zero. The range of values of number [i] is unbounded. A process may fail at any time. We assume that when it fails, it immediately goes to its noncritical section and halts. There may then be a period when reading from its memory gives arbitrary values. Eventually, any read from its memory must give a value of zero.

Code examples

Pseudocode In this example, all threads execute the same "main" function, Thread. In real applications, different threads often have different "main" functions. Note that as in the original paper, the thread checks itself before entering the critical section. Since the loop conditions will evaluate as false, this does not cause much delay.

Each thread only writes its own storage, only reads are shared. It is remarkable that this algorithm is not built on top of some lower level "atomic" operation, e.g. compare-and-swap. The original proof shows that for overlapping reads and writes to the same storage cell only the write must be correct. The read operation can return an arbitrary number. Therefore, this algorithm can be used to implement mutual exclusion on memory that lacks synchronisation primitives, e.g., a simple SCSI disk shared between two computers. The necessity of the variable Entering might not be obvious as there is no 'lock' around lines 7 to 13. However, suppose the variable was removed and two processes computed the same Number[i]. If the higher-priority process was preempted before setting Number[i], the low-priority process will see that the other process has a number of zero, and enters the critical section; later, the high-priority process will ignore equal Number[i] for lower-priority processes, and also enters the critical section. As a result, two processes can enter the critical section at the same time. The bakery algorithm uses the Entering variable to make the assignment on line 6 look like it was atomic; process i will never see a number equal to zero for a process j that is going to pick the same number as i. When implementing the pseudo code in a single process system or under cooperative multitasking, it is better to replace the "do nothing" sections with code that notifies the operating system to immediately switch to the next thread. This primitive is often referred to as yield. Lamport's bakery algorithm assumes a sequential consistency memory model. Few, if any, modern languages or multi-core processors implement such a memory model. Therefore, correct implementation of the algorithm typically requires inserting fences to inhibit reordering.

PlusCal code We declare N to be the number of processes, and we assume that N is a natural number.

We define P to be the set {1, 2, ... , N} of processes.

The variables num and flag are declared as global.

The following defines LL(j, i) to be true iff <<num[j], j>> is less than or equal to <<num[i], i>> in the usual lexicographical ordering.

… excerpt ends here. Continue reading the full article.

Worked examples

Example 1 — a first encounter with Lamport's bakery algorithm

Start with the simplest possible case. Write down what Lamport's bakery algorithm claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Lamport's bakery algorithm before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Lamport's bakery algorithm ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Lamport's bakery algorithm

In research
Lamport's bakery algorithm appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Lamport's bakery algorithm in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Lamport's bakery algorithm is common in secondary-school and first-year university syllabi. It links to neighbouring topics Concurrency control algorithms, so understanding it makes those chapters shorter.
In everyday life
Look for Lamport's bakery algorithm outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Lamport's bakery algorithm” →

How to study Lamport's bakery algorithm in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Lamport's bakery algorithm means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Lamport's bakery algorithm out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Lamport's bakery algorithm in simple terms?

Lamport's bakery algorithm is a computer algorithm devised by computer scientist Leslie Lamport, as part of his long study of the formal correctness of concurrent systems, which is intended to improve the safety in the usage of shared resources among multiple threads by means of mutual exclusion. I…

Why does Lamport's bakery algorithm matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Lamport's bakery algorithm?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Lamport's bakery algorithm.

Tags

  • Concurrency control algorithms

Keep exploring