Process Sempahores和死锁

Process Sempahores和死锁,process,parallel-processing,semaphore,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);

这是一个为我即将到来的考试而建议的练习,下面是我到目前为止收集的内容。所有建设性的投入将不胜感激

   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关于死锁和信号量编程的页面来做这个练习

好吧,以第一种情况为例

    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相同的顺序锁定P2(x,y,z而不是y,z,x)来修复。这可能意味着您必须在真正需要进行互斥之前锁定x,但这将防止死锁

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