Overview
The Library scenario simulates students (readers) accessing a catalog while a librarian (writer) periodically updates it. This demonstrates the readers-writer problem using a monitor to coordinate concurrent read access while ensuring exclusive write access.Real-World Problem
Consider a library database system:- Multiple students can read the catalog simultaneously
- When the librarian needs to update the catalog, no readers should be accessing it
- While an update is in progress, new readers must wait
- Readers should not block other readers
Shared Resources
The shared resource is a library catalog that supports:
- Concurrent read access by multiple students
- Exclusive write access by the librarian
- Version tracking to show catalog updates
Synchronization Algorithm
This scenario uses a Monitor implementing the readers-writer pattern:Reader Entry
Student calls
enterRead(). If no writer is active, multiple readers can proceed concurrently.Writer Entry
Librarian calls
enterWrite(), blocking until all readers finish and no other writer is activeScenario Setup
libraryScenario.js
Configuration Options
| Parameter | Description | Default |
|---|---|---|
readerCount | Number of student (reader) threads | Minimum 1 |
writerUpdates | Number of catalog updates by librarian | Minimum 1 |
Example Execution Flow
Thread Instructions
Student (Reader) threads:- ENTER_READ - Request read access (concurrent with other readers)
- READ_BOOK - Search for and read a specific book
- EXIT_READ - Release read access
- END - Terminate
- ENTER_WRITE - Request exclusive write access (blocks until no readers/writers)
- UPDATE_CATALOG - Modify catalog (increment version)
- EXIT_WRITE - Release write access
- Repeat for each update
- END - Terminate
The monitor ensures that:
- Multiple readers can access the catalog simultaneously
- Writers have exclusive access (no concurrent readers or writers)
- Readers and writers don’t starve (fairness policies apply)
Readers-Writer Patterns
Reader Priority
Writer Priority
Fair Policy
Monitor vs Mutex
| Aspect | Mutex | Readers-Writer Monitor |
|---|---|---|
| Concurrent Reads | No | Yes |
| Write Access | Exclusive | Exclusive |
| Complexity | Simple | Complex |
| Use Case | All operations exclusive | Read-heavy workloads |
Key Learning Points
- Concurrent Reads: Multiple students can read simultaneously
- Exclusive Writes: Librarian needs exclusive access for updates
- Monitor Pattern: Encapsulates synchronization logic
- Version Tracking: Updates increment catalog version
- Fairness: Implementation determines reader/writer priority
- Efficiency: Maximizes concurrency for read operations