Professional Documents
Culture Documents
OS Lec 11 Peterson Soution
OS Lec 11 Peterson Soution
OS Lec 11 Peterson Soution
Fall 2023
2
Text Book
►Process Synchronization
► Race Condition
► Critical Section
► Mutual Exclusion
Preamble (Past ► Progress
Process Synchronization
Shared variables:
int turn;
initially turn = 0
Process P0 Process P1
do { do {
while (turn!=0) ; while (turn!=1) ;
<CS> <CS>
turn = 1; turn = 0;
<RS> <RS>
} while (1); } while (1);
Shared variables
Process P0 Process P1
do { do {
flag[0] = true; flag[1] = true;
while (flag[1]) ; while (flag[0]) ;
<CS> <CS>
flag [0] = false; flag [1] = false;
<RS> <RS>
} while (1); } while (1);
Problem ? , Does it meet all conditions ?
Does not satisfy the progress condition, if both set flag at same time
Algorithm 3: Peterson’s Solution
The variable turn indicates whose turn it is to enter the critical section.
The flag array is used to indicate if a process is ready to enter the critical
section. flag[i] = true implies that process Pi is ready
Peterson’s Solution
Process P0 Process P1
do { do {
flag[0] = true; flag[1] = true;
turn = 1; turn = 0;
while (flag[1] && turn == 1); while (flag[0] && turn ==0);
<CS> <CS>
flag [0] = false; flag [1] = false;
<RS> <RS>
} while (1); } while (1);
Algorithm 3: Peterson’s Solution
If both processes want to enter their critical sections at the same time,
then flag[i] == flag[j] == true.