Readers-Writers Problem Simulation

5

Actors

Semaphore Status

Read Count: 0 | Write Lock: 0

Event Log

System initialized.

The Readers-Writers Problem

Problem Description

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:

  1. Multiple readers can access the shared resource simultaneously (since they don't modify it).
  2. Only one writer can access the shared resource at a time (to prevent data corruption).
  3. When a writer is accessing the resource, no reader can access it.

Challenges:

Solution Explanation

This simulation implements a solution with the following characteristics:

Approach Used:

The implementation uses semaphores to control access to the shared resource:

Reader Process:

  1. Check if no writer is active (writeLock === 0 && !writerBusy)
  2. If safe to read, increment readCount and begin reading
  3. When done reading, decrement readCount
  4. If readCount becomes 0, it signals that writers can now access the resource

Writer Process:

  1. Check if no readers are active (readCount === 0) and no other writer is active (writeLock === 0)
  2. If safe to write, set writeLock to 1 and begin writing
  3. When done writing, set writeLock back to 0
  4. Move to the next writer in the queue

Priority Mechanism:

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.

Pseudocode Algorithm

// 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