TP-systemes-concurrents/TP3/PhiloSem3.java

84 lines
2.7 KiB
Java
Raw Permalink Normal View History

2023-06-21 18:19:26 +00:00
import java.util.concurrent.Semaphore;
public class PhiloSem3 implements StrategiePhilo {
/****************************************************************/
Semaphore mutex = new Semaphore(1);
EtatPhilosophe[] etats;
Semaphore[] bloqueur;
boolean peutManger(int no) {
int pg = Main.PhiloGauche(no);
int pd = Main.PhiloDroite(no);
return etats[pg] != EtatPhilosophe.Mange && etats[pd] != EtatPhilosophe.Mange;
}
public PhiloSem3(int nbPhilosophes) throws InterruptedException {
this.bloqueur = new Semaphore[Main.nbPhilosophes];
this.etats = new EtatPhilosophe[Main.nbPhilosophes];
for (int i = 0; i < bloqueur.length; i++) {
bloqueur[i] = new Semaphore(0, true);
etats[i] = EtatPhilosophe.Pense;
}
}
/**
* Le philosophe no demande les fourchettes. Précondition : il n'en possède
* aucune. Postcondition : quand cette méthode retourne, il possède les deux
* fourchettes adjacentes à son assiette.
*/
public void demanderFourchettes(int no) throws InterruptedException {
mutex.acquire();
if (peutManger(no)) {
etats[no] = EtatPhilosophe.Mange;
mutex.release();
} else {
etats[no] = EtatPhilosophe.Demande;
mutex.release();
bloqueur[no].acquire();
}
int fg = Main.FourchetteGauche(no);
int fd = Main.FourchetteDroite(no);
IHMPhilo.poser(fg, EtatFourchette.AssietteDroite);
IHMPhilo.poser(fd, EtatFourchette.AssietteGauche);
}
/**
* Le philosophe no rend les fourchettes. Précondition : il possède les deux
* fourchettes adjacentes à son assiette. Postcondition : il n'en possède
* aucune. Les fourchettes peuvent être libres ou réattribuées à un autre
* philosophe.
*/
public void libererFourchettes(int no) throws InterruptedException {
int pg = Main.PhiloGauche(no);
int pd = Main.PhiloDroite(no);
mutex.acquire();
etats[no] = EtatPhilosophe.Pense;
if (peutManger(pg) && etats[pg] == EtatPhilosophe.Demande) {
etats[pg] = EtatPhilosophe.Mange;
bloqueur[pg].release();
}
if (peutManger(pd) && etats[pd] == EtatPhilosophe.Demande) {
etats[pd] = EtatPhilosophe.Mange;
bloqueur[pd].release();
}
mutex.release();
int fg = Main.FourchetteGauche(no);
int fd = Main.FourchetteDroite(no);
IHMPhilo.poser(fg, EtatFourchette.Table);
IHMPhilo.poser(fd, EtatFourchette.Table);
}
/** Nom de cette stratégie (pour la fenêtre d'affichage). */
public String nom() {
return "Sémaphores, strat 3: scrute voisin";
}
}