信号量和死锁

时间:2013-10-24 18:52:08

标签: process parallel-processing semaphore

这是为即将到来的考试提出的一项练习,其中最重要的是我迄今为止所收集的内容。所有建设性的意见将不胜感激。

   P1, P2 and P3 share three semaphores (x, y and z) each with 1 as initial value and three variables (a, b and c).

        P1:

        (1.1) wait(x);
        (1.2) a = a + 1;
        (1.3) wait(y);
        (1.4) b = b - a;
        (1.5) wait(z);
        (1.6) c = a + 2*b -c;
        (1.7) signal(z);
        (1.8) signal(y);
        (1.9) signal(x)


        Code for P2:

        (2.1) wait(y);
        (2.2) b = b*2;
        (2.3) wait(z);
        (2.4) c = c - b;
        (2.5) signal(y);
        (2.6) wait(x);
        (2.7) a = a + c;
        (2.8) signal(x);
        (2.9) signal(z)

        Code for P3:

        (3.1) wait(y);
        (3.2) b = b*2;
        (3.3) wait(z);
        (3.4) c = c - b;
        (3.5) signal(z);
        (3.6) signal(y);
        (3.7) wait(x);
        (3.8) a = a / 10;
        (3.9) signal(x)

    A. If P1 and P2 run concurrently on a computer with only a single CPU, is it possible for these two processes to get into a deadlock? If so, show one execution sequence of the code that results in the deadlock, and show how to revise P2 only (P1 is not changed) to prevent deadlock.

    B. If P1 and P3 are run concurrently on a computer with only a single CPU, is it possible for these two processes to get into a deadlock? If so, show one execution sequence of the code that results in the deadlock, and show how to revise P3 only (P1 is not changed) to prevent deadlock.

    The changes you make should not violate the mutual exclusion requirement on shared variable access.

A)我不确定它们何时陷入僵局的例子意味着什么?对我来说,似乎y会导致死锁,因为第1.3行将导致y变为-1,直到P2的2.5才会解锁。

要解决此问题,应将1.3移至1.5以下,因为这是在P2中释放y的时间。虽然使用x看起来会有其他冲突,但我不知道重新排列P1的好方法是在不改变P2的情况下解决这个问题。

B)这里看起来1.3(等待(y))再次引起问题,因为直到3.6才发出信号。然后决议是将其移至1.6?

之后

我正在尝试使用Wiki的Deadlock和Semaphore Programming页面来完成这个练习。

1 个答案:

答案 0 :(得分:1)

嗯,在第一种情况下作为例子;

    Sequence                       Holds lock on
    (1.1) wait(x);                 P1 x,  P2 -
    (1.2) a = a + 1;               P1 x,  P2 -
    (2.1) wait(y);                 P1 x,  P2 y
    (2.2) b = b*2;                 P1 x,  P2 y
    (2.3) wait(z);                 P1 x,  P2 yz
    (2.4) c = c - b;               P1 x,  P2 yz
    (2.5) signal(y);               P1 x,  P2 z
    (2.6) wait(x);                 P1 x,  P2 z   - P2 locks waiting for x
    (1.3) wait(y);                 P1 xy, P2 z
    (1.4) b = b - a;               P1 xy, P2 z
    (1.5) wait(z);                 P1 xy, P2 z   - P1 locks waiting for z

它可以 - 例如 - 通过按照与P1(x,y,z而不是y,z,x)相同的顺序锁定P2来修复。这可能意味着你必须在真正需要互相排斥之前锁定x,但这样可以防止死锁。

据我所知,P1和P3不能相互死锁,因为P3被锁定在序列y,z(跟随x,y,z序列,只是跳过x上的锁),然后释放锁,只锁定/解锁x。