没有死锁——但为什么呢?四个条件

No Deadlock - but why? Four conditions

我有一个生产者消费者问题并使用信号量解决了它,但无法正式解释我阻止了死锁所必需的四个条件中的哪一个。它不能是互斥访问或非抢占,这会留下循环等待或保持等待。我显然尝试在 insert 和 take 方法中获取两个资源,这暗示 hold 和 wait 存在。现在只剩下我应该阻止的循环等待,但是如何呢?还是我的推理有误,不是循环等待?

编辑: 由于人们反复问我我的代码有什么问题,因为死锁不会发生,我想说这没什么问题,我只是想知道为什么 这不可能发生。发生死锁需要满足四个条件,可以在此处找到 https://en.wikipedia.org/wiki/Deadlock#Necessary_conditions 。我显然至少阻止了一种情况,否则我的代码可能会导致死锁。现在我只想知道我阻止了哪些情况

我的缓冲区代码如下所示:

private String[] store;
private int capacity;

private int nextIn;
private int nextOut;

private Semaphore mutex = new Semaphore(1);
private Semaphore numAvail = new Semaphore(0); //available items to consume
private Semaphore numFree; //free slots in buffer

public Buffer(int capacity) {
    this.capacity = capacity;
    this.store = new String[capacity];
    numFree = new Semaphore(capacity);
}

public void insert(String item) {

    try {
        //acquire a free slot in the array
        numFree.acquire();

        //get permit to insert
        mutex.acquire();
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
    }

    //critical region - insert to body
    store[nextIn] = item;

    nextIn++;

    //when at end of array begin at index 0 again
    if (nextIn == capacity) {
        nextIn = 0;
    }

    //signal that there is an item available
    numAvail.release();

    //signal that another thread can consume or produce now
    mutex.release();
}

public String take() {
    String item;

    try {
        //check if item exists to consume
        numAvail.acquire();

        //get permit to take
        mutex.acquire();

    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
        ex.printStackTrace();
    }

    //critical region
    item = store[nextOut];

    nextOut++;

    if (nextOut == capacity) {
        nextOut = 0;
    }


    //signal other threads that they can consume or produce
    mutex.release();

    //signal that there is a free slot to insert now
    numFree.release();

    return item;
}

我相信你阻止了循环等待。

each process waits for a resource which is being held by another process时发生循环等待。

在您的示例中,在持有另一个资源时正在等待的唯一资源是互斥体。但是,持有互斥锁的线程永远不会等待任何事情。

要发生循环等待,持有互斥量的线程在拥有互斥量时需要等待一些东西。