# Disabling Peterson’s Solution for Mutual Exclusion

Q1. Explain Disabling Peterson’s Solution for mutual exclusion.

Ans. In 1981, G. L. Peterson discovered a much simpler way to achieve mutual exclusion; Peterson’s algorithm consists of two procedures written in ANSI C.

#define FALSE 0

#define TRUE 1

#define N 2

/*number of processes*/

int turns;

/*whose turn is it?*/

int interested[N];

/*all values initially 0 (FALSE)*/

void enter_region(int process)

/*process is 0 or 1 */

{

int other;

/* number of the other process*/

other=1-process;

/*the opposite of process*/

interested[process]=TRUE;

/*show that you are interested*/

turn=process;

/*set flag*/

while(turn==process && interested[other]==TRUE)

/* null statement*/;

}

void leave_region(int process)

/*process: who is leaving*/

{

interested[process]=FALSE;

/*indicate departure from critical region*/

}

Before using the shared variables (that is, before its critical region), each process calls enter_region with its own process number, 0 or 1, as parameter. This call will cause to wait, if need be, until it is safe to enter. After it has finished with the shared variables, the process calls leave_region to indicate that it is one and to allow the other process to enter, if it so desires.

Initially neither process is in its critical region. Now process0 calls enter_region. It indicates its interest by setting its array element and sets turn to 0. Since process1 is not interested, enter_region returns immediately. If process1 now makes a call to enter_region, it will hang there until interested[0] goes to FALSE, an event that only happens when process0 calls leave_region to exit the critical region.

Now consider the case that both processes call enter_region almost simultaneously. Both will store there process number in turn. Whichever store is done last is the one that counts; the first one is overwritten and lost. Suppose that proess1 stores lost, so turn is 1. When both processes come to the while statement, process0 executes its zero times and enters its critical region. Process1 loops and does not enter its critical region until process0 exits its critical region.

74 Views