TP-systemes-concurrents/TP4/LectRed_PrioLecteur.java
2023-06-21 20:19:26 +02:00

66 lines
1.7 KiB
Java

// Time-stamp: <08 Apr 2008 11:35 queinnec@enseeiht.fr>
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Lecteurs/rédacteurs stratégie d'ordonnancement: priorité aux lecteurs,
* implantation: avec un moniteur.
*/
public class LectRed_PrioLecteur implements LectRed {
Lock lock;
Condition requestRead;
Condition requestWrite;
boolean activeWriter;
int activeReaders;
public LectRed_PrioLecteur() {
lock = new ReentrantLock();
requestRead = lock.newCondition();
requestWrite = lock.newCondition();
activeWriter = false;
activeReaders = 0;
}
public void demanderLecture() throws InterruptedException {
lock.lock();
if (activeWriter) {
requestRead.await();
}
activeReaders++;
lock.unlock();
}
public void terminerLecture() throws InterruptedException {
lock.lock();
activeReaders--;
if (activeReaders == 0) {
requestWrite.signal();
}
lock.unlock();
}
public void demanderEcriture() throws InterruptedException {
lock.lock();
while (activeWriter || activeReaders > 0) {
requestWrite.await();
}
activeWriter = true;
lock.unlock();
}
public void terminerEcriture() throws InterruptedException {
lock.lock();
activeWriter = false;
requestRead.signalAll();
requestWrite.signalAll();
lock.unlock();
}
public String nomStrategie() {
return "Stratégie: Moniteur, prio lecteur.";
}
}