Last time we looked at the hardware-based solutions to the Critical Section Problem and now we will be learning about one of the most popular software-based solutions to the CSP. It is called Peterson's Solution.
Peterson's Solution
Peterson's Solution is an algorithmic solution to the critical section problem. it illustrates some of the complexities of software design that addresses the requirements of mutual exclusion, progress and bounded waiting. But because of how modern computer architectures perform instructions it does not guarantees that it will work properly.
while True:
flag[i] = True
turn = j
while flag[j] and turn == j:
# critical section
flag[i] = False
# remainder section
Peterson's Solution works only between two process that are alternating their execution between critical section and remainder section. These processes are numbered P0 and P1. It requires two processes to share data items.
turn = i
The variable turn
denotes which turn it is to enter its critical section and variable flag[i]
is used to indicate the the porcess 1 is ready to enter it critical seciton. Now we will se how the algorithm works.
First it will set the flag[i]
to True to indicate that it is ready to enter its critical section while also assigning j
to variable turn
to indicate that other processes can also enter their critical section and currently it is j
's turn to enter the section. Then it checks that if it is still j
's turn and it's flag is set to true other wise it will set it to false. After that the process whose flag is set to true will enter critical section.
This way:
- Mutual exclusion is preserved.
- The progress requirment is satisfied.
- The bounded-waiting requirement is met.
Disadvantages Of Peterson's Solution
- Only works for two processes at a time
- CPU time is wasted