What is the readers-writers problem, and how is it solved?
HardConceptProcess Synchronization
Answer
In the readers-writers problem, many threads share some data: readers only read it, while writers change it. Any number of readers may read at the same time, but a writer needs exclusive access, with no other writer and no reader present. The classic solution uses a semaphore rw = 1 for exclusive access, a semaphore mutex = 1 to protect a counter, and an integer readers = 0.
Writer: Reader:
wait(rw) wait(mutex); readers++; if (readers == 1) wait(rw); signal(mutex)
write read
signal(rw) wait(mutex); readers--; if (readers == 0) signal(rw); signal(mutex)
- The first reader locks writers out and the last reader lets them back in, so readers share access.
- Drawback: if readers keep arriving, a writer may starve. A writer-preference version fixes that but can starve readers; fair versions serve requests in arrival order.
- Libraries provide this as a read-write lock, such as
pthread_rwlock_tin C orReentrantReadWriteLockin Java.
Example: a railway timetable can be viewed by thousands of users at once, but viewers must wait while an admin updates it. If R1 and R2 are reading when writer W arrives, W waits; if R3 arrives before they finish, R3 joins them at once, which is exactly how W can starve.