This chapter introduces a specialized synchronization primitive that is an optimization over standard mutexes. While mutexes are excellent for safety, they can be a bottleneck in performance-critical applications where data is read much more often than it is modified.
1. The Core Objective: Reading vs. Writing (Section 8.1)
A standard Mutex is a blunt instrument: it blocks all other threads from entering a critical region.
- If Thread A is reading data, Thread B cannot read that same data until Thread A unlocks the mutex.
- This is inefficient if the data isn’t changing. Why block a reader just because someone else is also reading?
Read-Write Locks (often called rwlocks) solve this by distinguishing between two types of access:
- Read Access: Just looking at the data.
- Write Access: Modifying the data.
2. The Locking Rules
Stevens outlines the specific logic that makes rwlocks work. It is often called Shared-Exclusive Locking:
- The Read Lock (Shared):
- Rule: Any number of threads can hold the lock for reading simultaneously.
- Condition: This is only allowed if no thread currently holds the lock for writing.
- The Write Lock (Exclusive):
- Rule: Only one thread can hold the lock for writing.
- Condition: To get a write lock, no other thread can hold the lock for either reading or writing. The writer must have the resource entirely to itself.
3. The Analogy: The Bank Account
The text provides a classic analogy to explain this:
- Reading: Imagine multiple people wanting to check the balance of a bank account. It is perfectly safe for 10 people to look at the balance at the exact same time. They don’t interfere with each other.
- Writing: Now imagine someone wants to make a deposit (update the balance). For that split second, no one else should be looking at the balance (or they might see a wrong number), and certainly no one else should be writing. The depositor needs exclusive access.
4. Summary of Benefits
| Feature | Mutex | Read-Write Lock |
|---|---|---|
| Concurrency | Low (1 thread at a time) | High (Multiple readers allowed) |
| Safety | High | High |
| Use Case | General purpose | Read-Heavy data structures |