Readers Writers: Simple Version
roomEmpty = S(1)
mutex = S(1) //
nReader = 0 // Tracks the number of readers
writer
while (True) {
wait(roomEmpty);
// modify data
signal(roomEmpty);
}
reader
while (True) {
wait(mutex); // Prevent race condition between other readers, next section is critical section.
// CS BEGIN
nReader++; // Indicate you are try to enter critical section
if (nReader == 1) { // If you are the first reader,
wait(roomEmpty); // Lock the resource from writers
}
// CS END
signal(mutex);
// <Read data>
wait(mutex);
// CS BEGIN
nReader--; // Once you are done reading,
if (nReader == 0) { // If you are last reader, you can exit
signal(roomEmpty); // Unlock if you are the last reader
}
// CS END
signal(mutex);
}
Shortcoming: starvation
If many readers access the data structure, the writer ends up getting locked out.