秦点点丶

秦小晋不弱智智障反而美丽可爱啦!

导航

Peterson算法

 1 #define FALSE 0
 2 #define TRUE 1
 3 #define N 2               /*进程数量 */
 4  
 5  int turn;                 /* 现在轮到谁 */
 6  int interested[N];            /*所有值初始化为0 (FALSE) */
 7  
 8  void enter_region(int process)    /*进程是0还是1 */
 9  {
10      int other;             /* 其他进程号*/
11      other = 1 - process;        /*另一方进程*/
12      interested[process] = TRUE;   /* 表明所感兴趣的 */
13      turn = process;          /* 设置标志 */
14      while(turn == process && interested[other] == TRUE);  /*空语句 */
15  }
16  
17  void leave_region(int process)    /*进程:谁离开*/
18  {
19      interested[[process] = FALSE; /* 表示离开临界区*/
20  }

   现在先来看看该算法是如何工作的:开始,没有任何进程处于临界区中。现在,进程0调用enter_region,设置other为1,turn为0,并标识自己希望进入临界区,如果进程1现在(现在是指进程0调用了enter_region并返回,且在临界区中工作)调用enter_region,进程1将在此处挂起直到interested[0]的值变为FALSE(满足while死循环终止的条件,因为当进程1调用enter_region时,此时interested[other]即interested[0]已经有值TRUE),而interested[0]只有在进程0调用leave_region退出临界区时才发生

   现在再考虑两个进程几乎同时调用enter_region的情况:在一开始的设置(turn)中,他们都将自己的进程号存入,但只有速度慢的那个才有效,前一个因重写而丢失,假设进程1的速度慢,则turn值为1,当两个进程都运行到while时,进程0将循环0次并进入临界区,而进程1则不停循环而不能进入临界区

   关键在于while循环,先进入的进程必能通过死循环,因为interested[other]值为FALSE(程序开始的初始化),而后进入的进程则依赖于先进入的进程。而且如果前一个进程足够快,它可以再次进入临界区工作!!

posted on 2014-12-15 21:39  秦点点丶  阅读(1516)  评论(0编辑  收藏  举报