Peterson’s Algorithm for Mutual Exclusion

Peterson’s Algorithm:

Peterson’s Algorithm was developed by G.L. Peterson in 1981 for enforcing mutual exclusion. It is a simple algorithm for enforcing two processes of mutual exclusion with busy waiting.

Algorithm:

Program Petersons;
var favored process:(first,second);
p1 wants_to_enter, p2 wants_to_enter : Boolean;
procedure processone;
begin
while true do
begin
p1 wants_to_enter:=true;
favored process:=second;
while p2 wants_to_enter And favored process = second do
critical section one;
p1 wants_to_enter:=false;
otherwiseone
end;
procedure processtwo;
begin
while true do
begin
p2 wants_to_enter:=true;
favored process:=first;
while pi wants_to_enter And favored process = first do;
critical section two;
p2 wants_to_enter:=false;
otherwisetwo
end;
begin
p1 wants_to_enter=false;
p2 wants_to_enter=false;
favored process:=first;
parbegin
processone;
processtwo;
parend
end;