Patterncore
Read-write lock
Also called read-write lock, readers-writer lock, readers–writer lock, RW lock, shared-exclusive lock, MRSW lock.
A read-write lock lets many threads read shared data at the same time but gives a writer exclusive access. Its priority policy decides if waiting readers or a waiting writer go first.
- Family
- concurrency
- Intent
- Let threads that only read shared data run in parallel, and still give a thread that changes the data exclusive access, so that no reader sees a half-done write.
- Also called
- Readers-writer lock, Single-writer lock, Multi-reader lock, Push lock, MRSW lock
Intent
A read-write lock allows concurrent access for read-only operations, whereas write operations require exclusive access.1 Multiple threads can read the data in parallel, but a thread needs an exclusive lock to write or modify the data.1
Problem
Many threads read a shared data structure and a few threads change it. The structure cannot be updated atomically, and it is invalid until the update is complete, so no thread may read it during a write.1 A plain mutex protects the data, but then no two threads can access the data at the same time.2 That is sub-optimal, because a reader R2 waits for a reader R1 although two reads do not interfere.2
Solution
Give the lock two modes. A thread takes the read lock to read and the write lock to write. The lock can be held by an arbitrary number of readers or a single writer.3 When a writer is writing the data, all other writers and readers are blocked until the writer is finished writing.1
read lock write lock
reader 1 ──►┐ writer ──►┐
reader 2 ──►├─► shared data ├─► shared data
reader 3 ──►┘ (all at once) ┘ (alone; readers and
other writers wait)
Read-write locks are usually constructed on top of mutexes and condition variables, or on top of semaphores.1 The lock also needs a priority policy. A read-preferring lock gives priority to readers, and a write-preferring lock gives priority to writers.1 The Python example is write-preferring: a reader that arrives while a writer waits must wait too.
Example
The example first starts two readers. Each takes the read lock and then waits until the other one is also inside, which shows that the two hold the read lock at the same time. Then 4 readers each read a pair of values 1000 times, and a writer changes the pair 100 times. The writer sets the first value, yields, and then sets the second value. Each reader reads the first value, yields, and then reads the second value. The lock makes sure that no reader sees a pair with two different values, and that no reader is inside while the writer is.
two readers inside at once: True
reads: 4000
reads that saw a mixed pair: 0
writes: 100
writes that ran with a reader inside: 0
The examples for each language show the same program.
import threading
import time
class ReadWriteLock:
"""Many readers or one writer. A waiting writer stops new readers."""
def __init__(self):
self._cond = threading.Condition()
self._readers = 0 # threads that hold the read lock
self._writer = False # True while a thread holds the write lock
self._waiting_writers = 0
def acquire_read(self):
with self._cond:
while self._writer or self._waiting_writers:
self._cond.wait()
self._readers += 1
def release_read(self):
with self._cond:
self._readers -= 1
if self._readers == 0:
self._cond.notify_all()
def acquire_write(self):
with self._cond:
self._waiting_writers += 1
while self._writer or self._readers:
self._cond.wait()
self._waiting_writers -= 1
self._writer = True
def release_write(self):
with self._cond:
self._writer = False
self._cond.notify_all()
lock = ReadWriteLock()
pair = [0, 0] # the writer keeps the two values equal
counts = {"reads": 0, "mixed": 0, "writes": 0, "overlap": 0, "inside": 0}
counts_lock = threading.Lock()
# Part 1: two readers hold the read lock at the same time.
meeting = threading.Barrier(2, timeout=5)
met = []
def meet():
lock.acquire_read()
try:
meeting.wait() # returns only when both readers are inside
met.append(True)
except threading.BrokenBarrierError:
met.append(False)
finally:
lock.release_read()
# Part 2: readers and a writer share the pair.
def reader():
for _ in range(1000):
lock.acquire_read()
with counts_lock:
counts["inside"] += 1
x = pair[0]
time.sleep(0) # give the writer a chance to run here
y = pair[1]
with counts_lock:
counts["inside"] -= 1
counts["reads"] += 1
if x != y:
counts["mixed"] += 1
lock.release_read()
def writer():
for i in range(1, 101):
lock.acquire_write()
with counts_lock:
if counts["inside"]:
counts["overlap"] += 1
pair[0] = i
time.sleep(0)
pair[1] = i
counts["writes"] += 1
lock.release_write()
def run_all(targets):
threads = [threading.Thread(target=t) for t in targets]
for t in threads:
t.start()
for t in threads:
t.join()
run_all([meet, meet])
run_all([reader, reader, reader, reader, writer])
print("two readers inside at once:", all(met))
print("reads:", counts["reads"])
print("reads that saw a mixed pair:", counts["mixed"])
print("writes:", counts["writes"])
print("writes that ran with a reader inside:", counts["overlap"])
two readers inside at once: True
reads: 4000
reads that saw a mixed pair: 0
writes: 100
writes that ran with a reader inside: 0
- Verdict: idiom. The
threadingmodule givesCondition, and thisReadWriteLockclass is built from oneConditionwith a count of readers and a count of waiting writers.
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <shared_mutex>
#include <thread>
#include <vector>
std::shared_mutex rw;
int pair_[2] = {0, 0}; // the writer keeps the two values equal
std::atomic<int> inside{0}, reads{0}, mixed{0};
int main() {
// Part 1: two readers hold the read lock at the same time.
std::mutex m;
std::condition_variable cv;
int at_meeting = 0, met = 0;
std::vector<std::thread> meets;
for (int i = 0; i < 2; i++) {
meets.emplace_back([&] {
std::shared_lock<std::shared_mutex> read_lock(rw);
std::unique_lock<std::mutex> lk(m);
at_meeting++;
cv.notify_all();
if (cv.wait_for(lk, std::chrono::seconds(5), [&] { return at_meeting == 2; })) met++;
});
}
for (auto& t : meets) t.join();
// Part 2: readers and a writer share the pair.
int writes = 0, overlap = 0;
std::vector<std::thread> threads;
for (int r = 0; r < 4; r++) {
threads.emplace_back([] {
for (int n = 0; n < 1000; n++) {
std::shared_lock<std::shared_mutex> read_lock(rw);
inside++;
int x = pair_[0];
std::this_thread::yield(); // give the writer a chance to run here
int y = pair_[1];
inside--;
reads++;
if (x != y) mixed++;
}
});
}
threads.emplace_back([&] {
for (int i = 1; i <= 100; i++) {
std::unique_lock<std::shared_mutex> write_lock(rw);
if (inside > 0) overlap++;
pair_[0] = i;
std::this_thread::yield();
pair_[1] = i;
writes++;
}
});
for (auto& t : threads) t.join();
std::cout << "two readers inside at once: " << (met == 2 ? "True" : "False") << "\n";
std::cout << "reads: " << reads << "\n";
std::cout << "reads that saw a mixed pair: " << mixed << "\n";
std::cout << "writes: " << writes << "\n";
std::cout << "writes that ran with a reader inside: " << overlap << "\n";
}
two readers inside at once: True
reads: 4000
reads that saw a mixed pair: 0
writes: 100
writes that ran with a reader inside: 0
- Verdict: stdlib.
std::shared_mutexwithstd::shared_lockfor readers andstd::unique_lockfor the writer.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class Main {
static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
static final int[] pair = {0, 0}; // the writer keeps the two values equal
static final AtomicInteger inside = new AtomicInteger();
static final AtomicInteger reads = new AtomicInteger();
static final AtomicInteger mixed = new AtomicInteger();
static int writes = 0;
static int overlap = 0;
static void runAll(List<Thread> threads) throws InterruptedException {
for (Thread t : threads) t.start();
for (Thread t : threads) t.join();
}
public static void main(String[] args) throws Exception {
// Part 1: two readers hold the read lock at the same time.
CyclicBarrier meeting = new CyclicBarrier(2);
AtomicInteger met = new AtomicInteger();
List<Thread> meets = new ArrayList<>();
for (int i = 0; i < 2; i++) {
meets.add(new Thread(() -> {
lock.readLock().lock();
try {
meeting.await(5, TimeUnit.SECONDS); // returns only when both readers are inside
met.incrementAndGet();
} catch (Exception e) {
// the other reader did not arrive in time
} finally {
lock.readLock().unlock();
}
}));
}
runAll(meets);
// Part 2: readers and a writer share the pair.
List<Thread> threads = new ArrayList<>();
for (int r = 0; r < 4; r++) {
threads.add(new Thread(() -> {
for (int n = 0; n < 1000; n++) {
lock.readLock().lock();
try {
inside.incrementAndGet();
int x = pair[0];
Thread.yield(); // give the writer a chance to run here
int y = pair[1];
inside.decrementAndGet();
reads.incrementAndGet();
if (x != y) mixed.incrementAndGet();
} finally {
lock.readLock().unlock();
}
}
}));
}
threads.add(new Thread(() -> {
for (int i = 1; i <= 100; i++) {
lock.writeLock().lock();
try {
if (inside.get() > 0) overlap++;
pair[0] = i;
Thread.yield();
pair[1] = i;
writes++;
} finally {
lock.writeLock().unlock();
}
}
}));
runAll(threads);
System.out.println("two readers inside at once: " + (met.get() == 2 ? "True" : "False"));
System.out.println("reads: " + reads.get());
System.out.println("reads that saw a mixed pair: " + mixed.get());
System.out.println("writes: " + writes);
System.out.println("writes that ran with a reader inside: " + overlap);
}
}
two readers inside at once: True
reads: 4000
reads that saw a mixed pair: 0
writes: 100
writes that ran with a reader inside: 0
- Verdict: stdlib.
ReentrantReadWriteLockinjava.util.concurrent.locksgives a read lock and a write lock.
using System;
using System.Collections.Generic;
using System.Threading;
class Program
{
static readonly ReaderWriterLockSlim rw = new ReaderWriterLockSlim();
static readonly int[] pair = { 0, 0 }; // the writer keeps the two values equal
static int inside, reads, mixed, writes, overlap;
static void RunAll(List<Thread> threads)
{
foreach (var t in threads) t.Start();
foreach (var t in threads) t.Join();
}
static void Main()
{
// Part 1: two readers hold the read lock at the same time.
var meeting = new Barrier(2);
int met = 0;
var meets = new List<Thread>();
for (int i = 0; i < 2; i++)
{
meets.Add(new Thread(() =>
{
rw.EnterReadLock();
try
{
// Returns true only when both readers are inside.
if (meeting.SignalAndWait(TimeSpan.FromSeconds(5))) Interlocked.Increment(ref met);
}
finally
{
rw.ExitReadLock();
}
}));
}
RunAll(meets);
// Part 2: readers and a writer share the pair.
var threads = new List<Thread>();
for (int r = 0; r < 4; r++)
{
threads.Add(new Thread(() =>
{
for (int n = 0; n < 1000; n++)
{
rw.EnterReadLock();
try
{
Interlocked.Increment(ref inside);
int x = pair[0];
Thread.Yield(); // give the writer a chance to run here
int y = pair[1];
Interlocked.Decrement(ref inside);
Interlocked.Increment(ref reads);
if (x != y) Interlocked.Increment(ref mixed);
}
finally
{
rw.ExitReadLock();
}
}
}));
}
threads.Add(new Thread(() =>
{
for (int i = 1; i <= 100; i++)
{
rw.EnterWriteLock();
try
{
if (Volatile.Read(ref inside) > 0) overlap++;
pair[0] = i;
Thread.Yield();
pair[1] = i;
writes++;
}
finally
{
rw.ExitWriteLock();
}
}
}));
RunAll(threads);
Console.WriteLine("two readers inside at once: " + (met == 2 ? "True" : "False"));
Console.WriteLine("reads: " + reads);
Console.WriteLine("reads that saw a mixed pair: " + mixed);
Console.WriteLine("writes: " + writes);
Console.WriteLine("writes that ran with a reader inside: " + overlap);
}
}
two readers inside at once: True
reads: 4000
reads that saw a mixed pair: 0
writes: 100
writes that ran with a reader inside: 0
- Verdict: stdlib.
ReaderWriterLockSliminSystem.ThreadinggivesEnterReadLockandEnterWriteLock.
// One event loop runs these tasks. Each await is a point where another task can run.
class ReadWriteLock {
constructor() {
this.readers = 0; // tasks that hold the read lock
this.writer = false; // true while a task holds the write lock
this.waitingWriters = 0;
this.waiters = [];
}
wait() {
return new Promise((resolve) => this.waiters.push(resolve));
}
wakeAll() {
const waiters = this.waiters;
this.waiters = [];
for (const resolve of waiters) resolve();
}
async acquireRead() {
while (this.writer || this.waitingWriters > 0) await this.wait();
this.readers++;
}
releaseRead() {
this.readers--;
if (this.readers === 0) this.wakeAll();
}
async acquireWrite() {
this.waitingWriters++;
while (this.writer || this.readers > 0) await this.wait();
this.waitingWriters--;
this.writer = true;
}
releaseWrite() {
this.writer = false;
this.wakeAll();
}
}
const tick = () => new Promise((resolve) => setImmediate(resolve));
const lock = new ReadWriteLock();
const pair = [0, 0]; // the writer keeps the two values equal
const counts = { reads: 0, mixed: 0, writes: 0, overlap: 0, inside: 0 };
// Part 1: two readers hold the read lock at the same time.
let atMeeting = 0;
async function meet() {
await lock.acquireRead();
atMeeting++;
for (let i = 0; i < 1000 && atMeeting < 2; i++) await tick();
const met = atMeeting === 2;
lock.releaseRead();
return met;
}
// Part 2: readers and a writer share the pair.
async function reader() {
for (let n = 0; n < 1000; n++) {
await lock.acquireRead();
counts.inside++;
const x = pair[0];
await tick(); // give the writer a chance to run here
const y = pair[1];
counts.inside--;
counts.reads++;
if (x !== y) counts.mixed++;
lock.releaseRead();
}
}
async function writer() {
for (let i = 1; i <= 100; i++) {
await lock.acquireWrite();
if (counts.inside > 0) counts.overlap++;
pair[0] = i;
await tick();
pair[1] = i;
counts.writes++;
lock.releaseWrite();
}
}
async function main() {
const met = await Promise.all([meet(), meet()]);
await Promise.all([reader(), reader(), reader(), reader(), writer()]);
console.log("two readers inside at once:", met.every((m) => m) ? "True" : "False");
console.log("reads:", counts.reads);
console.log("reads that saw a mixed pair:", counts.mixed);
console.log("writes:", counts.writes);
console.log("writes that ran with a reader inside:", counts.overlap);
}
main();
two readers inside at once: True
reads: 4000
reads that saw a mixed pair: 0
writes: 100
writes that ran with a reader inside: 0
- Verdict: idiom. The tasks run on one event loop, and the
ReadWriteLockclass keeps the waiting tasks as promises that it resolves when the lock is released.
// One event loop runs these tasks. Each await is a point where another task can run.
class ReadWriteLock {
readers: number;
writer: boolean;
waitingWriters: number;
waiters: Array<() => void>;
constructor() {
this.readers = 0; // tasks that hold the read lock
this.writer = false; // true while a task holds the write lock
this.waitingWriters = 0;
this.waiters = [];
}
wait(): Promise<void> {
return new Promise<void>((resolve) => this.waiters.push(resolve));
}
wakeAll(): void {
const waiters = this.waiters;
this.waiters = [];
for (const resolve of waiters) resolve();
}
async acquireRead(): Promise<void> {
while (this.writer || this.waitingWriters > 0) await this.wait();
this.readers++;
}
releaseRead(): void {
this.readers--;
if (this.readers === 0) this.wakeAll();
}
async acquireWrite(): Promise<void> {
this.waitingWriters++;
while (this.writer || this.readers > 0) await this.wait();
this.waitingWriters--;
this.writer = true;
}
releaseWrite(): void {
this.writer = false;
this.wakeAll();
}
}
const tick = (): Promise<void> => new Promise<void>((resolve) => setImmediate(resolve));
const lock = new ReadWriteLock();
const pair: number[] = [0, 0]; // the writer keeps the two values equal
const counts = { reads: 0, mixed: 0, writes: 0, overlap: 0, inside: 0 };
// Part 1: two readers hold the read lock at the same time.
let atMeeting: number = 0;
async function meet(): Promise<boolean> {
await lock.acquireRead();
atMeeting++;
for (let i = 0; i < 1000 && atMeeting < 2; i++) await tick();
const met = atMeeting === 2;
lock.releaseRead();
return met;
}
// Part 2: readers and a writer share the pair.
async function reader(): Promise<void> {
for (let n = 0; n < 1000; n++) {
await lock.acquireRead();
counts.inside++;
const x = pair[0];
await tick(); // give the writer a chance to run here
const y = pair[1];
counts.inside--;
counts.reads++;
if (x !== y) counts.mixed++;
lock.releaseRead();
}
}
async function writer(): Promise<void> {
for (let i = 1; i <= 100; i++) {
await lock.acquireWrite();
if (counts.inside > 0) counts.overlap++;
pair[0] = i;
await tick();
pair[1] = i;
counts.writes++;
lock.releaseWrite();
}
}
async function main(): Promise<void> {
const met = await Promise.all([meet(), meet()]);
await Promise.all([reader(), reader(), reader(), reader(), writer()]);
console.log("two readers inside at once:", met.every((m) => m) ? "True" : "False");
console.log("reads:", counts.reads);
console.log("reads that saw a mixed pair:", counts.mixed);
console.log("writes:", counts.writes);
console.log("writes that ran with a reader inside:", counts.overlap);
}
main();
two readers inside at once: True
reads: 4000
reads that saw a mixed pair: 0
writes: 100
writes that ran with a reader inside: 0
- Verdict: idiom. The tasks run on one event loop, and the
ReadWriteLockclass keeps the waiting tasks as promises that it resolves when the lock is released.
package main
import (
"fmt"
"runtime"
"sync"
"sync/atomic"
"time"
)
var (
rw sync.RWMutex
pair [2]int // the writer keeps the two values equal
inside atomic.Int64
reads atomic.Int64
mixed atomic.Int64
)
// Part 1: two readers hold the read lock at the same time.
func meet(atMeeting *atomic.Int64, met *atomic.Int64, wg *sync.WaitGroup) {
defer wg.Done()
rw.RLock()
defer rw.RUnlock()
atMeeting.Add(1)
deadline := time.Now().Add(5 * time.Second)
for atMeeting.Load() < 2 && time.Now().Before(deadline) {
runtime.Gosched()
}
if atMeeting.Load() == 2 {
met.Add(1)
}
}
// Part 2: readers and a writer share the pair.
func reader(wg *sync.WaitGroup) {
defer wg.Done()
for n := 0; n < 1000; n++ {
rw.RLock()
inside.Add(1)
x := pair[0]
runtime.Gosched() // give the writer a chance to run here
y := pair[1]
inside.Add(-1)
reads.Add(1)
if x != y {
mixed.Add(1)
}
rw.RUnlock()
}
}
func writer(writes, overlap *int, wg *sync.WaitGroup) {
defer wg.Done()
for i := 1; i <= 100; i++ {
rw.Lock()
if inside.Load() > 0 {
*overlap++
}
pair[0] = i
runtime.Gosched()
pair[1] = i
*writes++
rw.Unlock()
}
}
func main() {
var atMeeting, met atomic.Int64
var wg sync.WaitGroup
wg.Add(2)
go meet(&atMeeting, &met, &wg)
go meet(&atMeeting, &met, &wg)
wg.Wait()
writes, overlap := 0, 0
wg.Add(5)
for r := 0; r < 4; r++ {
go reader(&wg)
}
go writer(&writes, &overlap, &wg)
wg.Wait()
fmt.Println("two readers inside at once:", map[bool]string{true: "True", false: "False"}[met.Load() == 2])
fmt.Println("reads:", reads.Load())
fmt.Println("reads that saw a mixed pair:", mixed.Load())
fmt.Println("writes:", writes)
fmt.Println("writes that ran with a reader inside:", overlap)
}
two readers inside at once: True
reads: 4000
reads that saw a mixed pair: 0
writes: 100
writes that ran with a reader inside: 0
- Verdict: stdlib.
sync.RWMutexgivesRLockfor readers andLockfor the writer.
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, RwLock};
use std::thread;
use std::time::{Duration, Instant};
fn main() {
// The writer keeps the two values equal.
let lock = Arc::new(RwLock::new((0u64, 0u64)));
// Part 1: two readers hold the read lock at the same time.
let at_meeting = Arc::new(AtomicUsize::new(0));
let meets: Vec<_> = (0..2)
.map(|_| {
let lock = Arc::clone(&lock);
let at_meeting = Arc::clone(&at_meeting);
thread::spawn(move || {
let _guard = lock.read().unwrap();
at_meeting.fetch_add(1, Ordering::SeqCst);
let deadline = Instant::now() + Duration::from_secs(5);
while at_meeting.load(Ordering::SeqCst) < 2 && Instant::now() < deadline {
thread::yield_now();
}
at_meeting.load(Ordering::SeqCst) == 2
})
})
.collect();
let met = meets.into_iter().all(|h| h.join().unwrap());
// Part 2: readers and a writer share the pair.
let inside = Arc::new(AtomicUsize::new(0));
let reads = Arc::new(AtomicUsize::new(0));
let mixed = Arc::new(AtomicUsize::new(0));
let mut readers = Vec::new();
for _ in 0..4 {
let (lock, inside) = (Arc::clone(&lock), Arc::clone(&inside));
let (reads, mixed) = (Arc::clone(&reads), Arc::clone(&mixed));
readers.push(thread::spawn(move || {
for _ in 0..1000 {
let guard = lock.read().unwrap();
inside.fetch_add(1, Ordering::SeqCst);
let x = guard.0;
thread::yield_now(); // give the writer a chance to run here
let y = guard.1;
inside.fetch_sub(1, Ordering::SeqCst);
reads.fetch_add(1, Ordering::SeqCst);
if x != y {
mixed.fetch_add(1, Ordering::SeqCst);
}
}
}));
}
let writer = {
let (lock, inside) = (Arc::clone(&lock), Arc::clone(&inside));
thread::spawn(move || {
let (mut writes, mut overlap) = (0, 0);
for i in 1..=100u64 {
let mut guard = lock.write().unwrap();
if inside.load(Ordering::SeqCst) > 0 {
overlap += 1;
}
guard.0 = i;
thread::yield_now();
guard.1 = i;
writes += 1;
}
(writes, overlap)
})
};
for r in readers {
r.join().unwrap();
}
let (writes, overlap) = writer.join().unwrap();
println!("two readers inside at once: {}", if met { "True" } else { "False" });
println!("reads: {}", reads.load(Ordering::SeqCst));
println!("reads that saw a mixed pair: {}", mixed.load(Ordering::SeqCst));
println!("writes: {}", writes);
println!("writes that ran with a reader inside: {}", overlap);
}
two readers inside at once: True
reads: 4000
reads that saw a mixed pair: 0
writes: 100
writes that ran with a reader inside: 0
- Verdict: stdlib.
std::sync::RwLockgivesreadandwrite, and each guard releases the lock when it is dropped.
Consequences
Benefits:
- Readers do not block each other, so read-mostly data gets more concurrency than with a mutex.1
- A read-preferring lock allows maximum concurrency.1
- A write-preferring lock avoids writer starvation, because no new reader can acquire the lock while a writer is queued and waiting for it.1
Liabilities:
- A read-preferring lock can lead to write-starvation if contention is high, because a writer cannot acquire the lock as long as at least one reading thread holds it.1
- A write-preferring lock allows less concurrency in the presence of writer threads, and each operation is more complex.1
- Upgrading a lock from read-mode to write-mode is prone to deadlocks. If two threads that hold reader locks both try to upgrade to writer locks, there is a deadlock.1 In Java, if a reader tries to acquire the write lock it will never succeed.4
- A thread that takes the read lock again can block. In Go, if a goroutine calls
Lockwhile readers hold the lock, new calls toRLockblock until the writer has acquired and released the lock, and this prohibits recursive read-locking.3 The Rust documentation shows a similar potential deadlock, because a writer which waits for the lock might or might not block concurrent calls toread.5
This program asks for the write lock while it still holds the read lock. The write lock waits until no thread holds the read lock, so the thread waits for itself:
This code runs but gives a wrong answer on purpose.
import threading
class ReadWriteLock:
def __init__(self):
self._cond = threading.Condition()
self._readers = 0
self._writer = False
def acquire_read(self):
with self._cond:
self._cond.wait_for(lambda: not self._writer)
self._readers += 1
def release_read(self):
with self._cond:
self._readers -= 1
self._cond.notify_all()
def acquire_write(self, timeout):
with self._cond:
free = lambda: not self._writer and self._readers == 0
if not self._cond.wait_for(free, timeout):
return False
self._writer = True
return True
def release_write(self):
with self._cond:
self._writer = False
self._cond.notify_all()
lock = ReadWriteLock()
cache = {}
def get_or_load(key):
lock.acquire_read()
try:
if key not in cache:
# Wrong: ask for the write lock while this thread holds the read lock.
if not lock.acquire_write(timeout=1):
return "upgrade timed out: the thread's own read lock blocks the write lock"
cache[key] = key.upper()
lock.release_write()
return cache[key]
finally:
lock.release_read()
print(get_or_load("a"))
upgrade timed out: the thread's own read lock blocks the write lock
To fix the program, release the read lock, take the write lock, and check the condition again, because another thread can change the data between the two locks.
When not to use it
Do not use a read-write lock when most operations write, or when each read is very short. Each operation on a write-preferring lock is more complex than an operation on one mutex.1 Do not use it when the data can be immutable: an immutable object needs no lock for reads.
Variants and related patterns
- Priority policies. A lock can be read-preferring, write-preferring, or unspecified with regard to priority.1 An unspecified priority can be preferable if it allows a more efficient implementation.1 The Rust
RwLockuses the policy of the operating system and does not guarantee a particular policy.5
The next program puts a writer and a second reader in the queue while a first reader holds the lock, and prints the order in which they enter:
import threading
import time
class ReadWriteLock:
def __init__(self, prefer_writers):
self.prefer_writers = prefer_writers
self.cond = threading.Condition()
self.readers = 0
self.writer = False
self.waiting_readers = 0
self.waiting_writers = 0
def acquire_read(self):
with self.cond:
self.waiting_readers += 1
while self.writer or (self.prefer_writers and self.waiting_writers):
self.cond.wait()
self.waiting_readers -= 1
self.readers += 1
def release_read(self):
with self.cond:
self.readers -= 1
self.cond.notify_all()
def acquire_write(self):
with self.cond:
self.waiting_writers += 1
while self.writer or self.readers:
self.cond.wait()
self.waiting_writers -= 1
self.writer = True
def release_write(self):
with self.cond:
self.writer = False
self.cond.notify_all()
def wait_until(test):
while not test():
time.sleep(0.001)
def entry_order(prefer_writers):
lock = ReadWriteLock(prefer_writers)
entered = []
def writer():
lock.acquire_write()
entered.append("writer")
lock.release_write()
def second_reader():
lock.acquire_read()
entered.append("reader 2")
lock.release_read()
lock.acquire_read() # reader 1 holds the read lock
w = threading.Thread(target=writer)
w.start()
wait_until(lambda: lock.waiting_writers == 1)
r = threading.Thread(target=second_reader)
r.start()
wait_until(lambda: entered or lock.waiting_readers == 1)
lock.release_read() # reader 1 leaves
w.join()
r.join()
return entered
print("read-preferring:", entry_order(prefer_writers=False))
print("write-preferring:", entry_order(prefer_writers=True))
read-preferring: ['reader 2', 'writer']
write-preferring: ['writer', 'reader 2']
- Fair mode. Java's
ReentrantReadWriteLockdoes not impose a reader or writer preference ordering, but supports an optional fairness policy.4 In fair mode, threads contend for entry using an approximately arrival-order policy.4 - Upgradable lock. Some read-write locks allow the lock to be atomically upgraded from read-mode to write-mode. To avoid the deadlock, only one thread at a time can hold the lock in "read-mode with intent to upgrade to write".1
- Downgrading. Java allows downgrading from the write lock to a read lock: acquire the write lock, then the read lock, and then release the write lock. Upgrading from a read lock to the write lock is not possible.4 In Go, an
RLockcannot be upgraded into aLock, nor can aLockbe downgraded into anRLock.3 - Alternatives. The read-copy-update (RCU) algorithm is one solution to the readers-writers problem, and it is wait-free for readers. The Linux kernel uses a seqlock for few writers.1
A scoped locking guard releases the read lock or the write lock when the block ends, as the C++ and Rust examples do.
Known uses
- POSIX
pthread_rwlock_t.1 - Java
ReadWriteLockandReentrantReadWriteLock.1 - .NET
System.Threading.ReaderWriterLockSlim.1 - C++
std::shared_mutexand Boostshared_mutexandupgrade_mutex.1 - Go
sync.RWMutexand Ruststd::sync::RwLock.1 SRWLockin the Windows API andrw_semaphorein the Linux kernel.1
References
- Readers–writer lock, Wikipedia, lead; Upgradable RW lock; Priority policies; Implementation; Programming language support; Alternatives
- Readers–writers problem, Wikipedia, lead; First readers–writers problem; Second readers–writers problem
- Go standard library, package sync, type RWMutex
- Java SE 21 API, java.util.concurrent.locks.ReentrantReadWriteLock, Acquisition order; Reentrancy; Lock downgrading
- The Rust Standard Library, std::sync::RwLock, the type description
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 9D9V70 Edit this page History Report an error Markdown