I am trying to understand the Peterson's algorithm and I came across this question. I traced the code and I wrote my observations. Please check my observation, Am I on the right track?
Question from Textbook: Suppose the are only two processes, one with pid
value 0 and one with pid
value 1. What is wrong with this concurrency algorithm?
while(True)
{
flag[pid] = 1
turn = 1-pid
while( flag[1-pid] && turn == 1-pid ); // busy wait
// critical section
...
// end of critical section
flag[pid] = 0
}
Tracing the code:
---------- Process 0: ---------- | ---------- Process 1: ----------
|
pid = 0 | pid = 1
flag[0] = 1 | flag[1] = 1
turn = 1 - 0 = 1 | turn = 1 - 1 = 0
|
while (flag[1 - 0] | while (flag[1 - 1]
&& turn == (1 - 0)) | && turn == (1 - 1))
|
// --> while (flag [1] && true) | // --> while (flag [0] && true)
// --> while (flag [1]) | // --> while (flag [0])
My observations
0
get out of it's while loop then it can set it's flag to false
( flag[0] = 0
) and causes the other process Not to run . Thus, process 0
can run twice and process 1 doesn't run at all. Further, it can also cause the process 1
to starve or vice versa. Peterson's Algorithm guarantees access to critical sections for both processes without any starvation .
flag
indicates the desire to enter the critical section
. turn
is used by a process to allow the other finish waiting and proceed to critical section
. critical section
it states it's desire is gone ( flag[pid] = False
). This allows the other one to enter the section. However, if one process, due to context switches, toggles it's flag
on and off without the other one noticing it, it still has to toggle it's turn
flag. Peterson's Algorithm works because, each process has the following mindset:
I would like to access the critical section. So, I'll wait my turn
So you see, everything works out just fine in the end. There is no starvation , each process progresses without being stuck , and critical section is accessed by both processes over and over again.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.