سؤال

I have to code a solution to the dining philosophers problem in Java using semaphores. The semaphore is done "by hand" creating a semaphore class. And looks like this:

package principal;
public class Semaforo {
private int valor;
private int esperando;
public Semaforo(int valor) {
    this.valor=valor;
    this.esperando=0;
}
public synchronized void down() {
    if (this.valor >0 ){
        this.valor--;
    } else {
        this.esperando++;
        try {
            wait();
        } catch (Exception e) {

        }
    }
}
public int getValor() {
    return valor;
}
public synchronized void up() {
    if (this.valor > 0) {
        this.valor++;
    } else {
        if (this.esperando >0 ) {
            notify();
            this.esperando--;
        } else {
            this.valor++;
        }
    }
}
}

I would be nice if I had a solution that avoids problems of concurrency like deadlocks, starvation, live-locks, and so on. I thought of having each philosopher eat at his own time, but I don't know how I could accomplish that with semaphores. How do I solve the dinning philosophers problem with semaphores in Java?

Any help is appreciated.

هل كانت مفيدة؟

المحلول

This (page 87) goes over the Dining Philosophers problem taken from Tanenbaum's Modern Operating Systems 3e. The problem is solved with sempahores in the C programming language.

نصائح أخرى

You don't need the esparanto field and you don't need to check the state of 'valor' every time you up() the number of available semaphores. I'm bored at work so I trimmed your code:

private class Semaforo {
    private int valor;

    public Semaforo(int valor) {
        this.valor=valor;
    }

    public int getValor() {
        return valor;
    }

    public synchronized void down() {
        if (this.valor >0 ){
            this.valor--;
        } else {
            try {
                wait();
            } catch (InterruptedException e) {}
        }
    }

    public synchronized void up() {
        this.valor++;
        notify();
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top