初始化信号量以避免死锁情况

时间:2018-06-10 10:27:44

标签: operating-system semaphore binary-semaphore

有两个并发进程P1,P2使用R1,R2共享资源:

 P1: 
 Compute;
 Use R1;
 Use R2;

 P2:
 Compute;
 Use R1;
 Use R2;

具有以下调度约束: 在P1访问R1之前,P2必须完全使用R1。 P1必须在P2访问R2之前完成R2的使用。

所需的二进制信号量的最小数量是多少?

如果答案是2,那么执行的顺序是什么?如何初始化信号量以使进程不进入死锁状态?

1 个答案:

答案 0 :(得分:0)

假设进程只运行一次,两个二进制信号量就足够了:

Semaphore S1 = 1; //1: semaphore taken
Semaphore S2 = 1;

P1: 
 Compute;
 Take S1; //P1 blocks here until P2 gives S1
 Use R1;
 Use R2; //P1 uses R2 before P2
 Give S2; //P1 gives S2, allowing P2 to use R2

P2:
 Compute;
 Use R1; //P2 directly uses R1
 Give S1; //P2 gives S1, which will unblock P1
 Take S2; //P2 blocks here until S2 is given by P1
 Use R2;