从视觉上看,死锁在哪里?为什么?如何avoid/fix?

Visually where is the Deadlock? Why? How to avoid/fix?

我正在尝试理解并解决以下问题。

The following program attempts to use a pair of semaphores t and s for mutual exclusion.

Initially: s = 1, t = 0.

    Thread 1    Thread 2
    --------    --------
1.  P(s);       P(s);
2.  V(s);       V(s);
3.  P(t);       P(t);
4.  V(t);       V(t);

请记住:

The P operation wastes time or sleeps until a resource protected by the semaphore becomes available, at which time the resource is immediately claimed.

The V operation is the inverse: it makes a resource available again after the process has finished using it.


1. Why does this program cause a deadlock?

2. What changes can be made to initial semaphore values to remove deadlock potential?


更新

根据评论,我能够更好地理解并在下面直观地说明死锁,所以如果我理解正确,请告诉我。

Here is how the deadlock happens, IF Thread 1 gets CPU Time before Thread 2:

How to fix this?

t 的值设置为 1

提示:您可以通过锁顺序避免死锁。例如,所有代码必须在锁定 t 之前锁定 s。这个问题演示了如果不是这种情况会发生什么。您可以 "make changes to the initial semaphore values" 以符合锁定顺序。

死锁发生在 Line 3。在这一行,Threads 都在持续等待获取资源 t 的锁。 t 的初始值为 0,这意味着它已经处于锁定状态,因此例如如果 Thread1 先到达 line 3 它会等待 t 的值变为 1 并且类似地在一段时间后 Thread2 将在同一行等待 t 变为 1。这样,两个进程将连续等待资源创建“死锁”。