A Simpler Solution: Peterson's Algorithm

This is a much simpler algorithm developed by Peterson. In a remarkable 1981 paper of less than two pages, Peterson developed and proved versions of his algorithm for both the 2-process case and the N-process case.

CONCEPT: Both the turn variable and the status flags are used, as in Dekker's algorithm. After setting our flag we immediately give away the turn. We then wait for the turn if and only if the other flag is set. By waiting on the and of two conditions, we avoid the need to clear and reset the flags.

INITIALIZATION:

	typedef char boolean;
	...
	shared boolean flags[n -1];
	shared int turn;
	...
	turn = ;
	...
	flags[i ] = FREE;
	...
	flags[j ] = FREE;
	...
ENTRY PROTOCOL (for Process ):
	/* claim the resource */
	flags[] = BUSY;

	/* give away the turn */
	turn = ;
	/* wait while the other process is using the resource *and* has the turn */
	while ((flags[] == BUSY) && (turn != )) {
	}
EXIT PROTOCOL (for Process ):
	/* release the resource */
	flags[] = FREE;
ANALYSIS: The mutual exclusion requirement is assured. Suppose instead that both processes are in their critical section. Since only one can have the turn, the other must have reached the while test before the process with the turn set its flag. But after setting its flag, the other process had to give away the turn. The process at the while test has already changed the turn and will not change it again, contradicting our assumption.

The progress requirement is assured. Again, the turn variable is only considered when both processes are using, or trying to use, the resource.

Deadlock is not possible. If both processes are testing the while condition, one of them must have the turn. That process will proceed.

Finally, bounded waiting is assured. When a process that has exited the CS reenters, it will give away the turn. If the other process is already waiting, it will be the next to proceed.