23  Readers-writers problem

The next classical problem, called the Reader-Writer Problem, pertains to any situation where a data structure, database, or file system is read and modified by concurrent threads. While the data structure is being written or modified it is often necessary to bar other threads from reading, in order to prevent a reader from interrupting a modification in progress and reading inconsistent or invalid data.

As in the producer-consumer problem, the solution is asymmetric. Readers and writers execute different code before entering the critical section. The synchronization constraints are:

  1. Any number of readers can be in the critical section simultaneously.

  2. Writers must have exclusive access to the critical section.

In other words, a writer cannot enter the critical section while any other thread (reader or writer) is there, and while the writer is there, no other thread may enter.

The exclusion pattern here might be called categorical mutual exclusion. A thread in the critical section does not necessarily exclude other threads, but the presence of one category in the critical section excludes other categories.

Puzzle: Use semaphores to enforce these constraints, while allowing readers and writers to access the data structure, and avoiding the possibility of deadlock.

23.1 Readers-writers hint

Here is a set of variables that is sufficient to solve the problem.

int readers = 0
mutex = Semaphore(1)
roomEmpty = Semaphore(1)

The counter readers keeps track of how many readers are in the room. mutex protects the shared counter.

roomEmpty is 1 if there are no threads (readers or writers) in the critical section, and 0 otherwise. This demonstrates the naming convention I use for semaphores that indicate a condition. In this convention, “wait” usually means “wait for the condition to be true” and “signal” means “signal that the condition is true”.

23.2 Readers-writers solution

The code for writers is simple. If the critical section is empty, a writer may enter, but entering has the effect of excluding all other threads:

roomEmpty.wait()
    critical section for writers
roomEmpty.signal()

When the writer exits, can it be sure that the room is now empty? Yes, because it knows that no other thread can have entered while it was there.

The code for readers is similar to the barrier code we saw in the previous section. We keep track of the number of readers in the room so that we can give a special assignment to the first to arrive and the last to leave.

The first reader that arrives has to wait for roomEmpty. If the room is empty, then the reader proceeds and, at the same time, bars writers. Subsequent readers can still enter because none of them will try to wait on roomEmpty.

If a reader arrives while there is a writer in the room, it waits on roomEmpty. Since it holds the mutex, any subsequent readers queue on mutex.

mutex.wait()
    readers += 1
    if readers == 1:
        roomEmpty.wait()     # first in locks
mutex.signal()

# critical section for readers

mutex.wait()
    readers -= 1
    if readers == 0:
        roomEmpty.signal()   # last out unlocks
mutex.signal()

The code after the critical section is similar. The last reader to leave the room turns out the lights—that is, it signals roomEmpty, possibly allowing a waiting writer to enter.

Again, to demonstrate that this code is correct, it is useful to assert and demonstrate a number of claims about how the program must behave. Can you convince yourself that the following are true?

  • Only one reader can queue waiting for roomEmpty, but several writers might be queued.

  • When a reader signals roomEmpty the room must be empty.

Patterns similar to this reader code are common: the first thread into a section locks a semaphore (or queues) and the last one out unlocks it. In fact, it is so common we should give it a name and wrap it up in an object.

The name of the pattern is Lightswitch, by analogy with the pattern where the first person into a room turns on the light (locks the mutex) and the last one out turns it off (unlocks the mutex). Here is a class definition for a Lightswitch:

class Lightswitch:
    def __init__(self):
        self.counter = 0
        self.mutex = Semaphore(1)

    def lock(self, semaphore):
        self.mutex.wait()
            self.counter += 1
            if self.counter == 1:
                semaphore.wait()
        self.mutex.signal()

    def unlock(self, semaphore):
        self.mutex.wait()
            self.counter -= 1
            if self.counter == 0:
                semaphore.signal()
        self.mutex.signal()

lock takes one parameter, a semaphore that it will check and possibly hold. If the semaphore is locked, the calling thread blocks on semaphore and all subsequent threads block on self.mutex. When the semaphore is unlocked, the first waiting thread locks it again and all waiting threads proceed.

If the semaphore is initially unlocked, the first thread locks it and all subsequent threads proceed.

unlock has no effect until every thread that called lock also calls unlock. When the last thread calls unlock, it unlocks the semaphore.

Using these functions, we can rewrite the reader code more simply:

readLightswitch = Lightswitch()
roomEmpty = Semaphore(1)

readLightswitch is a shared Lightswitch object whose counter is initially zero.

readLightswitch.lock(roomEmpty)
# critical section
readLightswitch.unlock(roomEmpty)

The code for writers is unchanged.

It would also be possible to store a reference to roomEmpty as an attribute of the Lightswitch, rather than pass it as a parameter to lock and unlock. This alternative would be less error-prone, but I think it improves readability if each invocation of lock and unlock specifies the semaphore it operates on.

23.3 Starvation

In the previous solution, is there any danger of deadlock? In order for a deadlock to occur, it must be possible for a thread to wait on a semaphore while holding another, and thereby prevent itself from being signaled.

In this example, deadlock is not possible, but there is a related problem that is almost as bad: it is possible for a writer to starve.

If a writer arrives while there are readers in the critical section, it might wait in queue forever while readers come and go. As long as a new reader arrives before the last of the current readers departs, there will always be at least one reader in the room.

This situation is not a deadlock, because some threads are making progress, but it is not exactly desirable. A program like this might work as long as the load on the system is low, because then there are plenty of opportunities for the writers. But as the load increases the behavior of the system would deteriorate quickly (at least from the point of view of writers).

Puzzle: Extend this solution so that when a writer arrives, the existing readers can finish, but no additional readers may enter.

23.4 No-starve readers-writers hint

Here’s a hint. You can add a turnstile for the readers and allow writers to lock it. The writers have to pass through the same turnstile, but they should check the roomEmpty semaphore while they are inside the turnstile. If a writer gets stuck in the turnstile it has the effect of forcing the readers to queue at the turnstile. Then when the last reader leaves the critical section, we are guaranteed that at least one writer enters next (before any of the queued readers can proceed).

readSwitch = Lightswitch()
roomEmpty = Semaphore(1)
turnstile = Semaphore(1)

readSwitch keeps track of how many readers are in the room; it locks roomEmpty when the first reader enters and unlocks it when the last reader exits.

turnstile is a turnstile for readers and a mutex for writers.

23.5 No-starve readers-writers solution

Here is the writer code:

turnstile.wait()
    roomEmpty.wait()
    # critical section for writers
turnstile.signal()

roomEmpty.signal()

If a writer arrives while there are readers in the room, it will block at Line 2, which means that the turnstile will be locked. This will bar readers from entering while a writer is queued. Here is the reader code:

turnstile.wait()
turnstile.signal()

readSwitch.lock(roomEmpty)
    # critical section for readers
readSwitch.unlock(roomEmpty)

When the last reader leaves, it signals roomEmpty, unblocking the waiting writer. The writer immediately enters its critical section, since none of the waiting readers can pass the turnstile.

When the writer exits it signals turnstile, which unblocks a waiting thread, which could be a reader or a writer. Thus, this solution guarantees that at least one writer gets to proceed, but it is still possible for a reader to enter while there are writers queued.

Depending on the application, it might be a good idea to give more priority to writers. For example, if writers are making time-critical updates to a data structure, it is best to minimize the number of readers that see the old data before the writer has a chance to proceed.

In general, though, it is up to the scheduler, not the programmer, to choose which waiting thread to unblock. Some schedulers use a first-in-first-out queue, which means that threads are unblocked in the same order they queued. Other schedulers choose at random, or according to a priority scheme based on the properties of the waiting threads.

If your programming environment makes it possible to give some threads priority over others, then that is a simple way to address this issue. If not, you will have to find another way.

Puzzle: Write a solution to the readers-writers problem that gives priority to writers. That is, once a writer arrives, no readers should be allowed to enter until all writers have left the system.

23.6 Writer-priority readers-writers hint

As usual, the hint is in the form of variables used in the solution.

readSwitch = Lightswitch()
writeSwitch = Lightswitch()
noReaders = Semaphore(1)
noWriters = Semaphore(1)

23.7 Writer-priority readers-writers solution

Here is the reader code:

noReaders.wait()
    readSwitch.lock(noWriters)
noReaders.signal()

    # critical section for readers

readSwitch.unlock(noWriters)

If a reader is in the critical section, it holds noWriters, but it doesn’t hold noReaders. Thus if a writer arrives it can lock noReaders, which will cause subsequent readers to queue.

When the last reader exits, it signals noWriters, allowing any queued writers to proceed.

The writer code:

writeSwitch.lock(noReaders)
    noWriters.wait()
        # critical section for writers
    noWriters.signal()
writeSwitch.unlock(noReaders)

When a writer is in the critical section it holds both noReaders and noWriters. This has the (relatively obvious) effect of insuring that there are no readers and no other writers in the critical section. In addition, writeSwitch has the (less obvious) effect of allowing multiple writers to queue on noWriters, but keeping noReaders locked while they are there. Thus, many writers can pass through the critical section without ever signaling noReaders. Only when the last writer exits can the readers enter.

Of course, a drawback of this solution is that now it is possible for readers to starve (or at least face long delays). For some applications it might be better to get obsolete data with predictable turnaround times.