OSTEP: Chapters 31
Semaphore usage generally falls into two classes:
Whenever possible, cast problems into the first class. This usually can be done.
Unfortunately, sometimes a resource is shared by different classes of users; that is, they use the resource in different ways. Potentially the different kinds of usage interact. For example, consider a shared database with readers and writers. It is safe for any number of readers to access the database simultaneously, but each writer must have exclusive access. Example: checking account (statement-generators are readers, tellers are writers).
AW is always 0 or 1. AR and AW may not both be non-zero.
Reader Process: | Writer Process: |
---|---|
StartRead () { P(Lock); if ((AW+WW) != 0) { WR++; V(Lock); P(OKToRead); } else { AR++; V(Lock); } } |
StartWrite () { P(Lock); if ((AW+AR+WW) != 0) { WW++; V(Lock); P(OKToWrite); } else { AW++; V(Lock); } } |
EndRead () { P(Lock); AR--; if ((AR == 0) and (WW > 0)) { V(OKToWrite); AW++; WW--; } V(Lock); } |
EndWrite () P(Lock); AW--; if (WW>0) { V(OKToWrite); AW++; WW--; } else { while (WR>0) { V(OKToRead); AR++; WR--; } } V(Lock); } |
main () { StartRead(); // --read the necessary data-- EndRead(); } |
main () { StartWrite(); // --write the necessary data-- EndWrite(); } |
Examples:
Questions: