Fair Read-Write Locks: The Turnstile Solution
The Turnstile Idea
All threads (readers and writers) must pass through a turnstile before entering. Normally the turnstile is open - threads pass right through. But a waiting writer locks the turnstile. New readers queue up behind it instead of barging in.
How It Guarantees Fairness
Writer arrives, locks turnstile, waits for current readers to finish. New readers see locked turnstile and queue. When last reader exits, writer enters. Writer finishes, unlocks turnstile. Queued readers proceed. At least one writer gets through before more readers can enter.
The Implementation
Reader: Pass through turnstile (may block if writer waiting). Increment reader count. If first reader, lock room from writers. Do work. Decrement count. If last reader, unlock room.
Writer: Lock turnstile (blocks new readers). Wait for room to be empty. Do work. Unlock room. Unlock turnstile (let queued readers through).
Trade-off: Fairness vs Throughput
Fair locks have lower throughput. Readers that could have proceeded now wait for writers. Choose based on your requirements: reader-preference for maximum read throughput, fair for bounded writer latency.