Lamport's bakery algorithm

Lamport's bakery algorithm

"Lamport's bakery algorithm" is a computer algorithm devised by computer scientist Dr. Leslie Lamport, which is intended to improve the safety in the usage of shared resources among multiple threads by means of mutual exclusion.

Nature of the problem

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 done shopping, the customer loses their number and can then do whatever they want, except for shopping without getting a new number.

In the computer world, the 'customers' will be threads, identified by the letter "i", obtained from a global variable.

Due to the limitations of computer architecture, some parts of the Lamport's analogy need slight modification. It is possible that more than one thread will get the same number when they request it; this cannot be avoided. Therefore, it is assumed that the thread identifier "i" is also a priority identifier. A lower value of "i" means a higher priority and threads with higher priority will enter the critical section 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 and others must wait.

When a thread wants to enter the critical section, it has to check whether it is its turn to do so. It should check the numbers 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 will be written in the form: (a, b) < (c, d)which is equivalent to: (a < c) or ((a = c) and (b < d))

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

Pseudocode

// "declaration and initial values of global variables" Entering: array [1..N] of bool = {false}; Number: array [1..N] of integer = {0}; 1 lock(integer i) { 2 Entering [i] = true; 3 Number [i] = 1 + max(Number [1] , ..., Number [N] ); 4 Entering [i] = false; 5 for (j = 1; j <= N; j++) { 6 // "Wait until thread j receives its number": 7 while (Entering [j] ) { /* nothing */ } 8 // "Wait until all threads with smaller numbers or with the same" 9 // "number, but with higher priority, finish their work": 10 while ((Number [j] != 0) && ((Number [j] , j) < (Number [i] , i))) { 11 /* nothing */ 12 } 13 } 14 } 15 16 unlock(integer i) { 17 Number [i] = 0; 18 } 19 20 Thread(integer i) { 21 while (true) { 22 lock(i); 23 // "The critical section goes here..." 24 unlock(i); 25 // "non-critical section..." 26 } 27 }

In this example, all threads execute the same "main" function, "Thread". In real applications, different threads often have different "main" functions.

Note: The thread also checks itself before entering the critical section, but that doesn't cause any delays since the loop conditions will evaluate as "false".

Discussion

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 variable "Entering" might not be obvious as there is no 'lock' around lines 7 to 13. See [http://nob.cs.ucdavis.edu/classes/ecs150-1999-02/sync-bakery.html UCDAVIS: Bakery Algorithm] for an in depth discussion.

When implementing the pseudo code for a single processor/core system, it is better to replace the "do nothing" sections with code that notifies the operating system to immediately switch to the next thread. This is often referred to as yielding the current thread.

See also

* Dekker's algorithm
* Peterson's algorithm

External links

* [http://www.onjava.com/pub/a/onjava/2006/04/05/ajax-mutual-exclusion.html Wallace Variation of Bakery Algorithm] which overcomes limitations of Javascript language
* [http://research.microsoft.com/users/lamport/pubs/pubs.html#bakery Lamport's Bakery Algorithm]

References

* [http://research.microsoft.com/users/lamport/pubs/bakery.pdf Original Paper]
* On his [http://research.microsoft.com/users/lamport/pubs/pubs.html#bakery publications page] , Lamport has added some remarks regarding the algorithm.


Wikimedia Foundation. 2010.

Игры ⚽ Поможем написать реферат

Look at other dictionaries:

  • Lamport's Distributed Mutual Exclusion Algorithm — is a contention based algorithm for mutual exclusion on a distributed system. Algorithm Nodal Properties# Every process maintains a queue of pending requests for entering critical section ordered according to the logical time… …   Wikipedia

  • Ricart-Agrawala algorithm — The Ricart Agrawala Algorithm is an algorithm for mutual exclusion on a distributed system. This algorithm is an extension and optimization of Lamport s Distributed Mutual Exclusion Algorithm, by removing the need for release messages. It was… …   Wikipedia

  • Maekawa's algorithm — is an algorithm for mutual exclusion on a distributed system. The basis of this algorithm is a quorum like approach where any one site needs only to seek permissions from a subset of other sites. Contents 1 Algorithm 1.1 Terminology 1.2 Algorithm …   Wikipedia

  • Raymond's algorithm — is a token based algorithm for mutual exclusion on a distributed system. It imposes a logical structure (a K ary tree) on distributed resources. As defined, each node has only a single parent, to which all requests to attain the token are made.… …   Wikipedia

  • Dekker's algorithm — is the first known correct solution to the mutual exclusion problem in concurrent programming. The solution is attributed to Dutch mathematician Th. J. Dekker by Edsger W. Dijkstra in his manuscript on cooperating sequential processes.[1] It… …   Wikipedia

  • Peterson's algorithm — is a concurrent programming algorithm for mutual exclusion that allows two processes to share a single use resource without conflict, using only shared memory for communication. It was formulated by Gary Peterson in 1981 at the University of… …   Wikipedia

  • Leslie Lamport — Infobox Scientist name = Leslie Lamport image width = 150px caption = birth date = February 7, 1941 birth place = New York City, New York death date = death place = residence = citizenship = nationality = ethnicity = field = Computer Science work …   Wikipedia

  • List of algorithms — The following is a list of the algorithms described in Wikipedia. See also the list of data structures, list of algorithm general topics and list of terms relating to algorithms and data structures.If you intend to describe a new algorithm,… …   Wikipedia

  • Список алгоритмов — Эта страница информационный список. Основная статья: Алгоритм Ниже приводится список алгоритмов, группированный по категориям. Более детальные сведения приводятся в списке структур данных и …   Википедия

  • Algorithme de la boulangerie — L algorithme de la boulangerie (Lamport s bakery algorithm en anglais) est un algorithme d exclusion mutuelle découvert par Leslie Lamport[1], dans le cadre général de machines multi processeurs à mémoire partagée ne fournissant aucune opération… …   Wikipédia en Français

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”