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

  现在先来看看该算法是如何工作的:开始,没有任何进程处于临界区中。现在,进程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(程序开始的初始化),而后进入的进程则依赖于先进入的进程。而且如果前一个进程足够快,它可以再次进入临界区工作!!

05-04 00:39