Lamport's Bakery Algorithm
   HOME

TheInfoList



OR:

Lamport's bakery algorithm is a computer
algorithm In mathematics and computer science, an algorithm () is a finite sequence of Rigour#Mathematics, mathematically rigorous instructions, typically used to solve a class of specific Computational problem, problems or to perform a computation. Algo ...
devised by computer scientist
Leslie Lamport Leslie B. Lamport (born February 7, 1941) is an American computer scientist and mathematician. Lamport is best known for his seminal work in distributed systems, and as the initial developer of the document preparation system LaTeX and the author ...
, as part of his long study of the formal correctness of
concurrent system Concurrency refers to the ability of a system to execute multiple tasks through simultaneous execution or time-sharing (context switching), sharing resources and managing interactions. Concurrency improves responsiveness, throughput, and scalabi ...
s, which is intended to improve the safety in the usage of shared resources among multiple threads by means of
mutual exclusion In computer science, mutual exclusion is a property of concurrency control, which is instituted for the purpose of preventing race conditions. It is the requirement that one thread of execution never enters a critical section while a concurr ...
. In
computer science Computer science is the study of computation, information, and automation. Computer science spans Theoretical computer science, theoretical disciplines (such as algorithms, theory of computation, and information theory) to Applied science, ...
, it is common for multiple threads to simultaneously access the same resources.
Data corruption Data corruption refers to errors in computer data that occur during writing, reading, storage, transmission, or processing, which introduce unintended changes to the original data. Computer, transmission, and storage systems use a number of meas ...
can occur if two or more threads try to write into the same
memory Memory is the faculty of the mind by which data or information is encoded, stored, and retrieved when needed. It is the retention of information over time for the purpose of influencing future action. If past events could not be remembe ...
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 In computer science, mutual exclusion is a property of concurrency control, which is instituted for the purpose of preventing race conditions. It is the requirement that one thread of execution never enters a critical section while a concurr ...
algorithms designed to prevent concurrent threads entering
critical sections In concurrent programming, concurrent accesses to shared resources can lead to unexpected or erroneous behavior. Thus, the parts of the program where the shared resource is accessed need to be protected in ways that avoid the concurrent access. One ...
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. Due to the limitations of computer architecture, some parts of Lamport's
analogy Analogy is a comparison or correspondence between two things (or two groups of things) because of a third element that they are considered to share. In logic, it is an inference or an argument from one particular to another particular, as oppose ...
need slight modification. 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 In concurrent programming, concurrent accesses to shared resources can lead to unexpected or erroneous behavior. Thus, the parts of the program where the shared resource is accessed need to be protected in ways that avoid the concurrent access. One ...
first.


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 In computer science, pseudocode is a description of the steps in an algorithm using a mix of conventions of programming languages (like assignment operator, conditional operator, loop) with informal, usually self-explanatory, notation of actio ...
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 and number are in the memory of process i, and are initially zero. * The range of values of number 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. // declaration and initial values of global variables Entering: array ..NUM_THREADSof bool = ; Number: array ..NUM_THREADSof integer = ; lock(integer i) unlock(integer i) Thread(integer i) 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 In computer science, compare-and-swap (CAS) is an atomic instruction used in multithreading to achieve synchronization. It compares the contents of a memory location with a given (the previous) value and, only if they are the same, modifies the ...
. 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 /code>. If the higher-priority process was preempted before setting Number /code>, 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 /code> 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 Cooperative multitasking, also known as non-preemptive multitasking, is a computer multitasking technique in which the operating system never initiates a context switch from a running Process (computing), process to another process. Instead, in o ...
, 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, languages or multi-core processors implement such a memory model. Therefore, correct implementation of the algorithm typically requires inserting fences to inhibit reordering.Chinmay Narayan, Shibashis Guha, S.Arun-Kuma
Inferring Fences in a Concurrent Program Using SC proof of Correctness
/ref>


PlusCal code

We declare N to be the number of processes, and we assume that N is a natural number. CONSTANT N ASSUME N \in Nat We define P to be the set of processes. P

1..N
The variables num and flag are declared as global. --algorithm AtomicBakery


Java code

We use the AtomicIntegerArray class not for its built in atomic operations but because its get and set methods work like volatile reads and writes. Under the Java Memory Model this ensures that writes are immediately visible to all threads. AtomicIntegerArray ticket = new AtomicIntegerArray(threads); // ticket for threads in line, n - number of threads // Java initializes each element of 'ticket' to 0 AtomicIntegerArray entering = new AtomicIntegerArray(threads); // 1 when thread entering in line // Java initializes each element of 'entering' to 0 public void lock(int pid) // thread ID public void unlock(int pid)


See also

*
Dekker's algorithm Dekker's algorithm is the first known correct solution to the mutual exclusion problem in concurrent programming where processes only communicate via shared memory. The solution was attributed to Dutch people, Dutch mathematician Theodorus Dekker, ...
* Eisenberg & McGuire algorithm *
Peterson's algorithm Peterson's algorithm (or Peterson's solution) is a concurrent programming algorithm for mutual exclusion that allows two or more processes to share a single-use resource without conflict, using only shared memory for communication. It was formulate ...
*
Szymański's algorithm Szymański's Mutual Exclusion Algorithm is a mutual exclusion algorithm devised by computer scientist Dr. Bolesław Szymański, which has many favorable properties including linear wait, and which extension solved the open problem posted by Lesl ...
* Semaphores


References

{{Reflist
Original Paper
* On hi

Lamport has added some remarks regarding the algorithm.


External links



which overcomes limitations of Javascript language

from the original on 2018-05-06.


Another JavaScript implementation
by a.in.the.k Concurrency control algorithms Articles with example pseudocode