首页 > 试题广场 >

考虑具有如下特征的共享资源:(1)使用该资源的进程个数小于3

[问答题]
考虑具有如下特征的共享资源:(1)使用该资源的进程个数小于3时,新申请资源的进程可立刻获得资源;(2)当三个资源都被占用时,只有当前使用资源的三个进程都释放资源后,其他申请资源的进程才能获得资源。由于需要使用计数器来记录有多少进程正在使用资源和等待资源,而这些计数器自身也需要互斥执行修改动作的共享资源,所以可以采用如下程序:
1 semaphore mutex =1, block = 0;                     /*share vatiables : semaphores */
2 int active = 0, waiting = 0;                       /*counters, and */
3 boolean must_wait = false;                         /* state information */
4 
5 semWait (mutex);                                   /*Enter the mutual exclusion */
6 if (must_wait){                                    /* If there are ( or were) 3 , then */
7    ++waiting;                                  /* we must wait , but we must leave  */ 
8 semSignal (mutex);                                           /* the mutual exclusion first  */
9 semWait (block);                                             /* Wait for all current users to depart */
10 semwait (mutex);                                            /* Reenter the mutual exclusion*/
11--waiting;                                                    /* and update the waiting count*/
12}
13 ++active;                                                    /* Update active count , and remember*/
14 must_wait = active == 3;                                 /* if the count reached 3    */
15semsignal (mutex);                                           /* Leave the mutual exclusion    */
16
17 /* critical section * /
18
19 semWait (mutex);                                             /* Enter mutual exclusion    */
20 --active ;                                                   /* and update the active count */
21 if( active == 0){                                           /* Last one to leave? */
22     int n;
23     if (waiting < 3) n = waiting;
24        else n = 3;                                           /* If so, unblock up to 3    */
25     while (n > 0){                                           /* waiting processes    */
26         semsignal (block );
27         --n;
28 }
29 must_wait = false;                                             /* All active process have left */
30 }
31 semSignal (mutex);                                               /* Leave the mutual exclusion */
这个程序看起来没有问题:所有对共享数据的访问均被临界区保护,进程在临界区中执行时自身不会阻塞,新进程在有三个资源使用者存在时不能使用共享资源,最后一个离开的使用者会唤醒最多 3 个等待的进程。
a.这个程序仍不正确,解释其出错的位置。
b.若将第 6 行的 if 语句更换为 while 语句,是否能解决上面的问题?有什么难点仍然存在?

这段代码的目的是控制对共享资源的访问,确保在资源被占用时,新的进程必须等待。程序中的错误和解决方案如下:

a. 错误位置:第6行的if语句可能导致进程在不应该等待的情况下等待,因为must_wait可能已经被其他进程改变。

b. 解决方案:将if更换为while语句可以确保进程只在必须等待时才等待。但是,这样做可能会引入新的问题,比如饥饿,因为等待的进程可能会被新到达的进程无限期地推迟。

发表于 2023-11-04 20:39:41 回复(0)