CMSC 421 Operating Systems Lecture Notes (c) 1994 Howard E. Motteler Interprocess Communication Example: Readers and Writers -------------------------------------------------------- A simple, semi-fair readers and writers solution using a state variable with any form of mutual exclusion. States: Free: no active readers or writers AR: one or more readers are active AW: one writer is active S is single semaphore, used for mutual exclusion, and readcnt is the number of active readers Initially S = 1, readcnt = 0, state = Free, and k the desired time between tests of the state variable WRITER: while (alive) { wait(S); while (state == AR || state == AW) { signal(S); sleep(k); wait(S); } state = AW; signal(S); write_stuff(); wait(S); state = Free; signal(S); } READER: while (alive) { wait(S); while (state == AW) { signal(S); sleep(k); wait(S); } state = AR; readcnt++; signal(S); read_stuff(); wait(S); readcnt--; if (readcnt == 0) state = Free; signal(S); } Similarly to the TSL instruction, this solution does not guarantee bounded waiting for a fixed bound. If the process scheduler is fair, however, no reader or writer is locked out permanently.