Course contentsShow
← Computer Science
Lesson 1311 of 2,87230. Process SynchronizationFree lesson

Reader-Writer Problem with CVs

Solve the readers-writers problem using condition variables to manage multiple reader and exclusive writer access.

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, and waiting_writers

Reader logic:

  1. Lock the mutex
  2. While a writer is active, wait on can_read CV
  3. Increment active_readers
  4. Unlock mutex, read data
  5. Lock mutex, decrement active_readers
  6. If last reader leaving and writers waiting, signal can_write

Writer logic:

  1. Lock the mutex
  2. Increment waiting_writers
  3. While readers or writers active, wait on can_write CV
  4. Decrement waiting_writers, set active_writers = 1
  5. Unlock mutex, write data
  6. Lock mutex, set active_writers = 0
  7. Broadcast can_read or signal can_write for 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.