Synchronization

the readers–writers problem

Think of a reference book on a library table. Any number of people can read it at the same time without bothering each other — reading does not change the page. But if a librarian wants to write a correction, everyone else must step back: no one may read while it is being edited, and only one editor at a time. The readers-writers problem is how to allow many simultaneous readers of shared data while still giving writers exclusive, solitary access.

The standard tool is a reader-writer lock (rwlock), a lock with two modes. A reader takes it in shared mode: many readers may hold it shared at once. A writer takes it in exclusive mode: a writer waits until there are no readers and no other writer, then holds it alone. In code you call rwlock_rdlock() before reading and rwlock_wrlock() before writing, unlocking after. The whole point is to win back concurrency that a plain mutex throws away: with an ordinary mutex even two readers serialise, which is wasteful when reads vastly outnumber writes. The subtle design choice is policy — if readers keep arriving, a 'reader-preferring' lock may make a waiting writer wait forever (writer starvation); a 'writer-preferring' policy fixes that by blocking new readers once a writer is waiting, at the cost of some reader throughput.

Reader-writer locks shine for data that is read far more often than written — a configuration table, a routing cache, an in-memory index. But they are not a free upgrade over a mutex. A reader-writer lock is heavier than a plain mutex (it must track a reader count), so for short critical sections or roughly balanced read/write mixes a simple mutex is often faster. And they introduce the starvation worry above. The honest rule: reach for one only when you have measured that read-mostly contention is the actual bottleneck.

Readers: rwlock_rdlock(&L); v = config[key]; rwlock_unlock(&L); — many run concurrently. Writer: rwlock_wrlock(&L); config[key] = newv; rwlock_unlock(&L); — runs alone, with no readers present.

Shared mode for readers (many at once), exclusive mode for writers (one, alone).

A reader-writer lock can starve writers (or readers, depending on its policy) — read the policy your library implements rather than assuming fairness. It is also not automatically faster than a mutex: the extra reader-counting overhead can lose to a plain mutex for short or write-heavy critical sections.

Also called
reader-writer lockshared/exclusive lockrwlock讀寫鎖共享/獨佔鎖