问题
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
- I think in the busy waiting sections, both while loops may run forever.
- I also think when one of the processes for example process
0get out of it's while loop then it can set it's flag tofalse(flag[0] = 0) and causes the other process Not to run. Thus, process0can run twice and process 1 doesn't run at all. Further, it can also cause the process1to starve or vice versa.
回答1:
Peterson's Algorithm guarantees access to critical sections for both processes without any starvation.
flagindicates the desire to enter thecritical section.turnis used by a process to allow the other finish waiting and proceed tocritical section.- When a process finish it's job at the
critical sectionit 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'sflagon and off without the other one noticing it, it still has to toggle it'sturnflag.
Summary
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.
来源:https://stackoverflow.com/questions/26693414/trying-to-understand-the-petersons-algorithm