[Solved] Deadlock occuring in the Dining Philosophers code


The solution is relatively simple:

  1. Philosopher attempts to get fork on left
    SUCCEED -> Continue to step 2
    FAIL -> wait (for a while)
  2. Philosopher attempts to get fork on right
    SUCCEED -> Continue to step 3
    FAIL -> Release left fork and wait (for a while)
  3. Eat and release both forks. Then wait (for a while)

The point to emphasize here is that anytime a philosopher fails to get both forks, he needs to drop any forks he is holding and wait a bit or deadlock will eventually occur.

Perhaps more importantly, what kind of moron uses two forks to eat?

— EDIT —

Here is a quick example for the Fork

class Fork {
    public static final char FORK = '|';
    public static final char NO_FORK = ' ';
    private int id;
    private Lock lock = new ReentrantLock();

    public Fork(final int id) {
        this.id = id;
    }

    public boolean isHeld() {
        return lock.isLocked();
    }

    // returns true if successfully grabbed!
    public synchronized boolean tryToGrab() {
        return lock.tryLock();
    }

    public void letGo() {
        lock.unlock();
    }
}

Your idea of using a Semaphore object would work just as well. Good luck!

13

solved Deadlock occuring in the Dining Philosophers code