Lamport proposed a bakery algorithm, a software solution, for the n process mutual exclusion problem. This algorithm solves a critical problem, following the fairest, first come, first serve principle.
Algorithm of Lamport's bakery algorithm
do
{
entering[i] := true; // show interest in critical section
// get a token number
number[i] := 1 + max(number[0], number[1], ..., number[n - 1]);
entering [i] := false;
for ( j := 0 ; j<n; j++)
{
// busy wait until process Pj receives its token number
while (entering [j])
{ ; } // do nothing
while (number[j] != 0 && (number[j], j) < (number[i], i)) // token comparison
{ ; } // do nothing
}
// critical section
number[i] := 0; // Exit section
// remainder section
} while(1);
Structure of process Pi for Lamport's bakery algorithm to critical section problem.
Explanation -
This algorithm uses the following two Boolean variables.
boolean entering[n];
int number[n];
All entering variables are initialized to false, and n integer variables numbers are all initialized to 0. The value of integer variables is used to form token numbers.
When a process wishes to enter a critical section, it chooses a greater token number than any earlier number.
Consider a process Pi wishes to enter a critical section, it sets
entering[i] to true to make other processes aware that it is choosing a token number. It then chooses a token number greater than those held by other processes and writes its token number. Then it sets entering[i] to false after reading them. Then It enters a loop to evaluate the status of other processes. It waits until some other process Pj is choosing its token number.
Pi then waits until all processes with smaller token numbers or the same token number but with higher priority are served fast.
When the process has finished with its critical section execution, it resets its number variable to 0.
The Bakery algorithm meets all the requirements of the critical section problem.
Advantages of Lamport's bakery algorithm
Disadvantages of Lamport's bakery algorithm
10 videos|99 docs|33 tests
|
|
Explore Courses for Computer Science Engineering (CSE) exam
|