Synchronization PatternsRead-Write LocksMedium⏱️ ~2 min

What is a Read-Write Lock?

Definition
A read-write lock allows multiple readers to access a resource simultaneously, but writers get exclusive access. Readers share, writers exclude everyone.

The Problem With Regular Mutexes

A regular mutex allows only one thread at a time. But reading does not modify data. If 10 threads want to read, why make 9 of them wait? They are not interfering with each other. Only writes cause trouble.

The Library Analogy

Think of a library reference book. Multiple people can read it at the same time - they just look over each others shoulders. But if someone wants to write in the margins, everyone else must leave. The writer needs the book to themselves.

Read-Write Lock Access Rules
ReadersCan share with other readersCannot enter if writer presentWritersExclusive access onlyNo readers, no other writers

The Two Rules

Rule 1: Any number of readers can be in the critical section at the same time. They do not interfere with each other.

Rule 2: Writers get exclusive access. No other readers or writers can be present. A writer blocks everyone.

When Read-Write Locks Shine

Read-write locks are worth the complexity when reads vastly outnumber writes. A configuration cache that is read 1000 times per second but updated once per hour. A routing table that is queried constantly but changes rarely.

Trade-off: Read-write locks have more overhead than simple mutexes. If writes are frequent, the extra bookkeeping costs more than it saves. Use them when read-to-write ratio is at least 10:1.
💡 Key Takeaways
Read-write locks allow multiple concurrent readers but only one writer. Readers share, writers exclude.
Regular mutexes are too restrictive for read-heavy workloads. Making readers wait for each other wastes concurrency.
Rule 1: Any number of readers simultaneously. Rule 2: Writers get exclusive access, blocking all others.
Best for high read-to-write ratios (10:1 or more). Configuration caches, routing tables, lookup structures.
More complex than simple mutex. Only use when the concurrency gain justifies the overhead.
📌 Examples
1DNS cache: Thousands of lookups per second, updates every few minutes. Perfect for read-write lock.
2Configuration manager: Read on every request, write on admin change. Readers should not block each other.
3In-memory database index: Queries run constantly, index rebuilds are rare. Let queries run concurrently.
← Back to Read-Write Locks Overview
What is a Read-Write Lock? | Read-Write Locks - System Overflow