Course contentsShow
← Rust
Lesson 1029 of 1,9109. Smart Pointers and Interior MutabilityFree lesson

RwLock for Granular Concurrent Access

Balance read and write contention in high-performance shared-state systems.

In this lesson, you will learn how to optimize high-performance shared state by using RwLock to distinguish between read-heavy and write-rare operations.

While a Mutex is excellent for general synchronization, it implements a strict "mutual exclusion" policy: only one thread can access the data at a time, regardless of whether it intends to read or modify the contents. This becomes a bottleneck in scenarios where many threads need to read a configuration or cache, but writes occur infrequently.

RwLock (Read-Write Lock) solves this by allowing multiple concurrent readers or exactly one writer. By separating the acquisition of read and write guards, you grant the system the ability to scale throughput when contention is dominated by read operations.

Understanding the Trade-off

Consider a shared cache protected by an Arc<RwLock<T>>:

use std::sync::{Arc, RwLock};

let cache = Arc::new(RwLock::new(vec![1, 2, 3]));

// Multiple threads can read simultaneously
let reader1 = cache.read().unwrap();
let reader2 = cache.read().unwrap();
assert_eq!(reader1[0], 1);

// The writer must wait for all active readers to drop their guards
// Once write() is called, subsequent reads are blocked until the writer finishes
let mut writer = cache.write().unwrap();
writer.push(4);

Balancing Contention

The power of RwLock lies in its granular access. When you invoke read(), the lock tracks the number of active readers. As long as no writer holds the lock, any number of threads can access the data concurrently. However, the write() method acts as a gatekeeper: it requests exclusive access, waiting for all existing readers to drop their guard before modifying the memory.

Be mindful that "granular" does not mean "free." Under extreme read-write contention, RwLock can introduce overhead compared to a Mutex because the implementation must maintain state for the reader count. Always profile your specific access patterns; use Mutex when state changes are frequent and fast, but reach for RwLock when your application performs significantly more reads than writes.

Key Takeaway: Use RwLock to achieve higher concurrency in read-heavy shared states by allowing multiple readers to hold access simultaneously while enforcing exclusive access for writes.