Semaphores Critical section : S Read gate : R Write gate : W Shared variables ar /* number of active readers */ rr /* number of running readers */ wexists /* flag indicating whether the writer process exists */ Initial values S = 1 /* only one process at a time */ R = 5 /* five concurrent readers */ W = 0 /* update process should be explicitly woken up */ ar = rr = wexists = 0 Code for reader (search process) P(S); /* enter critical section */ ++ar; /* a new reader has become active */ if ((!wexists) && (rr < 5)) /* proceed to the read area */ ++rr; /* this process will be running */ V(S); /* leave critical section */ P(R); /* wait on R */ /* read request granted, so this process will continue until end */ read database; P(S); /* enter critical section */ --ar; --rr; /* this running reader is going to terminate */ if (!wexists) if (ar > rr) /* there is a waiting reader */ ++rr; /* a waiting reader will switch from active to running */ V(R); /* do this anyway (even if there is no waiting reader) */ else /* do nothing, unless this is the last running reader */ if (rr == 0), then V(W); /* wake up the writer */ V(S); /* leave critical section */ Code for writer (update process) P(S); /* enter critical section */ wexists = 1; Set R = 0; /* no new active reader will be granted read access */ if (rr > 0) V(S); /* leave critical section */ P(W); /* wait until all running readers finish */ else V(S); /* leave critical section */ /* write request granted, so this process will continue until end */ update database; P(S); /* enter critical section */ Let t = min(5,ar); /* the count of active readers to wake up */ Do V(R) exactly t times; /* wake up t waiting readers */ rr = t; /* count of running readers */ Set R = 5 - t; /* remaining count of readers that can be allowed */ wexists = 0; V(S); /* leave critical section */