7-Semaphore Example Readers and Writers
7-Semaphore Example Readers and Writers
Whenever possible, cast problems into the first class. This usually can be done.
o Initialization:
semaphore OKToRead = new semaphore(0);
semaphore OKToWrite = new semaphore(0);
semaphore = new semaphoreLock(1);
int AR = 0, WR = 0, AW = 0, WW = 0;
Lock.P(); Lock.P();
AR--; AW--;
if ((AR == 0) and (WW > 0)) { if (WW>0) {
OKToWrite.V(); OKToWrite.V();
AW++; AW++;
WW--; WW--;
} } else {
Lock.V(); while (WR>0) {
OKToRead.V();
AR++;
WR--;
}
}
Lock.V();
Examples: