Readers Writers Problem¶
Another classic problem in concurrency is the Readers Writers problem. Like Producer Consumer, there are two classes of threads that operate on a shared data structure. Unlike Producer Consumer, the two classes of threads in the Readers Writers problem operate a bit differently. Writers are threads that modify data in a shared resource. These modifications could include adding new elements, removing existing elements, or changing the value of particular elements. Readers on the other hand are threaders that simply read the values of existing elements.
A race condition can result if two or more Writers try to modify the same resource. Likewise if a Writer tries to modify an resource that a Reader is trying to access, a race condition can occur. However, if two or more readers try to access the same resource (and there are no Writers in involved), a race condition does not occur.
In this visualizations below, Reader and Writer threads share a common data store. While the Readers can operate simultaneously on the shared data store, only one writer can access (in this case add to) the data store at a time. The goal is to come up with a strategy that enables all the threads to operate on the data store in a manner that is thread-safe (i.e., does not result in race conditions).
The following combined video illustrates multiple prioritization strategies:
Balanced Priorities¶
The following video illustrates a strategy that attempts to give Reader and Writer threads equal (or “balanced”) priority when accessing the shared data source:
Writer Priority¶
In the following video, Writer threads are given priority. Therefore, waiting Writers will always go ahead waiting Readers. Readers can only access elements when there are no Writers waiting to add elements to the shared data store.
Reader Priority¶
In the following video, Reader threads are given priority. Therefore, all Writers must wait until all Readers have finished reading elements before adding to the shared data store.