The Readers-Writers problem is a classic synchronization problem in operating systems and concurrent programming. It involves multiple processes (or threads) that need to access a shared resource, where:
Requirements:
Challenges:
This simulation implements a solution with the following characteristics:
The implementation uses semaphores to control access to the shared resource:
This implementation uses a round-robin approach for writers. Writers are processed in a circular queue to ensure fairness among them. The current implementation doesn't give explicit priority to either readers or writers, but in heavy reader traffic, writers might experience starvation.
// Semaphores and Variables
readCount = 0 // Number of readers currently reading
writeLock = 0 // Binary semaphore for write access (0: unlocked, 1: locked)
writerBusy = false // Flag to indicate if a writer is active
// Reader Process
function reader_process(reader_id):
while true:
if writeLock == 0 AND NOT writerBusy:
readCount++ // Increment reader count
// Critical Section - Reading
perform_read_operation()
readCount-- // Decrement reader count
else:
wait_for_access() // Reader must wait
// Writer Process
function writer_process(writer_id):
while true:
if readCount == 0 AND writeLock == 0 AND NOT writerBusy:
writerBusy = true
writeLock = 1 // Acquire write lock
// Critical Section - Writing
perform_write_operation()
writeLock = 0 // Release write lock
writerBusy = false
else:
wait_for_access() // Writer must wait