Reader-Writer Problem with CVs
What you'll learn: How to use condition variables to allow many readers simultaneous access while ensuring writers get exclusive control of shared data.
The Core Challenge
Remember the reader-writer problem: multiple threads want to read shared data (safe when done together), but writers need exclusive access (no readers or other writers allowed). You've solved this with semaphores and reader-writer locks—now you'll use condition variables for finer-grained control.
The Condition Variable Approach
Think of a library study room: readers can share the space, but when someone needs to reorganize the shelves (write), everyone must leave and no one else can enter.
Key components:
- Mutex: protects counters tracking active readers/writers
- Condition variables: signal when it's safe to read or write
- Counters: track
active_readers,active_writers, andwaiting_writers
Reader logic:
- Lock the mutex
- While a writer is active, wait on
can_readCV - Increment
active_readers - Unlock mutex, read data
- Lock mutex, decrement
active_readers - If last reader leaving and writers waiting, signal
can_write
Writer logic:
- Lock the mutex
- Increment
waiting_writers - While readers or writers active, wait on
can_writeCV - Decrement
waiting_writers, setactive_writers = 1 - Unlock mutex, write data
- Lock mutex, set
active_writers = 0 - Broadcast
can_reador signalcan_writefor next writer
This gives you precise control: writers can be prioritized by checking waiting_writers before allowing new readers.
Key Takeaway: Condition variables solve the reader-writer problem by letting you explicitly control when readers or writers proceed based on current activity state, offering more flexibility than semaphores alone for complex synchronization patterns.