Concurrency Foundations
local graph
Chapter 17 — Concurrency Foundations
Section titled “Chapter 17 — Concurrency Foundations”Divide et impera. (Divide and conquer.)
Object-oriented languages approach concurrency with a fundamental tension: their core abstraction (mutable objects with encapsulated state) conflicts with the requirements of safe concurrent access. A class that works flawlessly in single-threaded code becomes a source of data races when accessed from multiple threads. OOP languages address this through discipline, documentation, and runtime mechanisms like synchronized methods or locks. The burden falls on developers to remember which objects require synchronization, which locks protect which data, and what order prevents deadlocks. Mistakes produce bugs that manifest rarely, reproduce poorly, and corrupt data silently.
Rust takes a different approach. The ownership system covered in Chapter 2, which governs single-threaded memory safety, extends naturally to concurrency. The compiler tracks which data can be shared between threads and which data can be mutated, rejecting programs that would race at compile time. This guarantee, what Rust calls “fearless concurrency,” does not eliminate all concurrent programming challenges. Deadlocks remain possible. Logic errors in concurrent algorithms persist. But the most insidious class of bugs, data races where two threads access the same memory with at least one writing, cannot occur in safe Rust. The type system makes them unrepresentable.
Threads and thread safety guarantees
Rust’s standard library provides threads through std::thread, offering an interface familiar to developers from other languages. The spawn function creates a new thread, accepting a closure that becomes the thread’s entry point. The function returns a JoinHandle that allows waiting for the thread to complete and retrieving its result.
The conceptual model matches what OOP languages provide. A thread is an independent execution context with its own stack. Multiple threads share the process’s address space, able to access the same heap-allocated data. Threads execute concurrently, potentially in parallel on multi-core systems. The operating system schedules threads, and their relative execution order is non-deterministic.
What differs is how Rust controls access to shared data. Consider spawning a thread that accesses a variable from the parent scope:
fn main() { let data = vec![1, 2, 3];
let handle = thread::spawn(|| { println!("Data: {:?}", data); // Error: closure may outlive current function });
handle.join().unwrap();}This code fails to compile. The closure captures data by reference, but the spawned thread might outlive the scope where data exists. In a language like Java or C#, this code would compile and might even work, depending on timing. The garbage collector would keep data alive as long as any thread references it. In Rust, the compiler sees a potential use-after-free and rejects it.
The solution is moving ownership into the thread:
fn main() { let data = vec![1, 2, 3];
let handle = thread::spawn(move || { println!("Data: {:?}", data); // data is owned by this closure });
handle.join().unwrap(); // data is no longer accessible here - it moved into the thread}The move keyword transfers ownership of captured variables into the closure. The thread now owns data exclusively. No other thread can access it because ownership has transferred. The parent scope cannot use data after spawning because the value has moved. What would be a runtime race condition in other languages becomes a compile-time ownership violation in Rust.
This principle extends to all concurrent scenarios. When data moves into a thread, that thread owns it exclusively. When data must be shared, explicit types like Arc (atomic reference counting) manage the sharing. When data must be mutated from multiple threads, synchronization primitives like Mutex control access. The compiler enforces these requirements through two marker traits: Send and Sync.
Send and Sync: the concurrency contracts
Chapter 2 introduced Send and Sync as the marker traits that govern thread safety. This section explores them in the context of practical concurrent programming.
The Send and Sync traits are unusual among Rust traits. They have no methods, no associated types, nothing to implement. They exist purely as markers that communicate properties about types to the compiler. A type is Send if ownership can safely transfer to another thread. A type is Sync if references to it can safely be shared between threads.
Most types in Rust are both Send and Sync automatically. Primitive types, structs containing only Send types, enums with only Send variants, and standard collections all derive these traits. The compiler implements them automatically when safe to do so. This automatic derivation means developers rarely think about these traits until they encounter a type that lacks them.
Types that are not Send include those with thread-affine resources. A MutexGuard, the type returned when locking a mutex, is not Send because some operating systems require unlocking to happen on the same thread that locked. Raw pointers are neither Send nor Sync because the compiler cannot reason about what they point to. Reference-counted pointers using Rc are not Send because their reference counts are not atomic; incrementing from multiple threads could corrupt the count.
Types that are Send but not Sync include Cell and RefCell. These types allow interior mutability through shared references, but their mechanisms are not thread-safe. A Cell<i32> can be sent to another thread (where it will be used exclusively), but references to it cannot be shared across threads because concurrent modifications would race.
The distinction matters in practice. Consider a function that spawns a thread:
fn process_in_thread<T: Send + 'static>(data: T) -> JoinHandle<T> { thread::spawn(move || { // process data data })}The bound T: Send ensures only transferable types can be passed. The ‘static bound ensures the data contains no borrowed references that could dangle. These bounds are what thread::spawn actually requires; attempting to spawn a thread with non-Send data fails at compile time with an error explaining the trait bound.
The Sync trait enables shared references across threads:
fn share_between_threads<T: Sync + Send + 'static>(data: Arc<T>) { let d1 = Arc::clone(&data); let d2 = Arc::clone(&data);
let h1 = thread::spawn(move || { println!("Thread 1 sees: {:?}", d1); });
let h2 = thread::spawn(move || { println!("Thread 2 sees: {:?}", d2); });
h1.join().unwrap(); h2.join().unwrap();}The Arc (atomic reference counting) type enables shared ownership across threads. Each thread holds a clone of the Arc, which increments the atomic reference count. All clones point to the same underlying data. The T: Sync bound ensures that the shared references (provided through Arc::deref) are safe to use concurrently.
The following diagram illustrates how Send and Sync govern data flow between threads:
graph TD
subgraph MT["Main Thread"]
T["T: Send + Sync"]
end
subgraph T1["Thread 1"]
A1["&T (via Arc)"]
end
subgraph T2["Thread 2"]
A2["&T (via Arc)"]
end
T -- "Arc::new + clone<br/>(requires Send)" --> A1
T -- "Arc::new + clone<br/>(requires Send)" --> A2
A1 -. "shared read<br/>(requires Sync)" .- A2
[!visual-conversion] Send enables transfer; Sync enables shared access. Print diagram (PDF 461, printed p. 453) recreated in Mermaid; labels verbatim, the “shared read” link is dotted in print.
These traits form the foundation of Rust’s concurrency safety. The compiler uses them to verify thread safety at compile time. When code compiles, it cannot have data races. This guarantee holds even for complex scenarios involving multiple threads, shared state, and conditional synchronization.
Arc and Mutex: shared mutable state
Chapter 2 introduced the smart pointer types Box, Rc, and Arc. Single-threaded Rust uses Rc for shared ownership and RefCell for interior mutability. Neither is thread-safe. Concurrent programming requires their thread-safe counterparts: Arc for shared ownership and Mutex for mutual exclusion.
Arc<T> (atomic reference counting) provides shared ownership
where multiple threads can hold references to the same heap-allocated
data. Unlike Rc, Arc uses atomic operations for reference count
manipulation, making increment and decrement safe across threads.
The data inside an Arc is immutable through shared references, just
as with any shared reference in Rust.
Mutex<T> provides mutual exclusion, allowing exactly one thread to
access the protected data at a time. Calling lock() on a mutex blocks
until the lock is available, then returns a guard that provides access to
the inner data. When the guard drops (goes out of scope), the lock
releases automatically. This RAII pattern ensures locks are always
released, even when panics occur.
Combining these types creates the standard pattern for shared mutable state:
use std::sync::{Arc, Mutex};use std::thread;
fn main() { let counter = Arc::new(Mutex::new(0)); let mut handles = vec![];
for _ in 0..10 { let counter = Arc::clone(&counter); let handle = thread::spawn(move || { let mut num = counter.lock().unwrap(); *num += 1; }); handles.push(handle); } for handle in handles { handle.join().unwrap(); }
println!("Result: {}", *counter.lock().unwrap());}The Arc<Mutex<i32>> structure provides both shared ownership (Arc) and mutable access (Mutex). Each thread clones the Arc, gaining shared ownership. The lock() call blocks until exclusive access is available, then returns a MutexGuard<i32> that dereferences to &mut i32. The increment happens under the lock’s protection. When the guard drops at the end of the scope, the lock releases.
The unwrap() calls deserve attention. Mutex::lock() returns a Result because acquiring a mutex can fail if a thread panicked while holding the lock. This state, called “poisoning,” indicates that the protected data may be in an inconsistent state. Calling unwrap() propagates the panic if poisoning occurred. In production code, the choice between propagating, recovering, or explicitly handling poisoned state depends on the application’s requirements.
The type system prevents misuse. Attempting to share Mutex<T> without Arc fails because Mutex does not implement Clone. Attempting to access the data without locking fails because Mutex<T> does not implement Deref. The only path to the inner data goes through lock(). The types guide developers toward correct usage rather than relying on documentation and discipline.
This pattern differs from OOP approaches in important ways. In Java, any object can be synchronized using the synchronized keyword or explicit Lock objects. The relationship between locks and the data they protect is implicit, maintained by programmer convention. In Rust,
Mutex<T> explicitly wraps the protected data. The type system enforces that access goes through the mutex. A developer cannot accidentally access the data without locking because the data is literally inside the mutex.
I have found this explicitness valuable when working on concurrent code. In OOP codebases, I spent considerable time tracing which locks protected which data, maintaining mental maps that documentation often failed to capture. In Rust, the type tells me everything: Mutex<DatabaseConnection> protects a database connection, and I can only reach that connection through the mutex.
RwLock: Read-Write synchronization
Mutex provides exclusive access regardless of operation type. When reads significantly outnumber writes, this exclusivity wastes potential parallelism. Multiple readers could safely access data simultaneously; only writes require exclusion. RwLock (read-write lock) optimizes for this scenario.
An RwLock<T> allows multiple readers or a single writer, but not both. Calling read() acquires a shared read lock, blocking only if a writer holds the lock. Multiple read locks can exist simultaneously. Calling write() acquires an exclusive write lock, blocking until all current readers and writers release their locks.
use std::sync::{Arc, RwLock};use std::thread;
fn main() { let config = Arc::new(RwLock::new(Configuration::default()));
// Spawn readers let mut handles = vec![]; for id in 0..5 { let config = Arc::clone(&config); handles.push(thread::spawn(move || { for _ in 0..100 { let cfg = config.read().unwrap(); process_with_config(id, &cfg); // read lock released here } })); }
// Spawn writer let config_writer = Arc::clone(&config); handles.push(thread::spawn(move || { for i in 0..10 { thread::sleep(Duration::from_millis(50)); let mut cfg = config_writer.write().unwrap(); cfg.update_setting(i); // write lock released here } }));
for handle in handles { handle.join().unwrap(); }}The five reader threads can all read simultaneously when no writer is active. When the writer acquires its lock, readers wait until the write completes. This pattern suits scenarios like configuration that changes rarely but is read frequently, caches with occasional invalidation, or shared lookup tables.
Choosing between Mutex and RwLock involves trade-offs. RwLock has higher overhead per operation due to more complex state tracking. For short critical sections or balanced read/write ratios, Mutex often performs better. RwLock excels when reads are long or substantially outnumber writes. Benchmarking with realistic workloads reveals which performs better for a specific use case.
RwLock also risks writer starvation if readers arrive continuously. Most implementations prioritize writers to prevent this, but behavior varies. The standard library’s RwLock does not guarantee fairness, and different platforms may exhibit different behaviors. When fairness matters, third-party crates like parking_lot provide locks with explicit fairness guarantees.
Avoiding deadlocks
Static compile-time guarantees prevent data races but not deadlocks. Deadlock occurs when threads wait for each other in a cycle: thread A holds lock 1 and waits for lock 2, while thread B holds lock 2 and waits for lock 1. Neither can proceed. The program hangs silently, consuming no CPU while making no progress.
The classic deadlock scenario:
let lock_a = Arc::new(Mutex::new(0));let lock_b = Arc::new(Mutex::new(0));
let a1 = Arc::clone(&lock_a);let b1 = Arc::clone(&lock_b);let handle1 = thread::spawn(move || { let _a = a1.lock().unwrap(); thread::sleep(Duration::from_millis(10)); // Increase chance of interleaving let _b = b1.lock().unwrap(); // Waits for lock_b println!("Thread 1 done");});
let a2 = Arc::clone(&lock_a);let b2 = Arc::clone(&lock_b);let handle2 = thread::spawn(move || { let _b = b2.lock().unwrap(); thread::sleep(Duration::from_millis(10)); let _a = a2.lock().unwrap(); // Waits for lock_a println!("Thread 2 done");});Thread 1 acquires lock_a then tries to acquire lock_b. Thread 2 acquires lock_b then tries to acquire lock_a. If their timing interleaves poorly, each holds one lock and waits for the other. Neither thread can proceed.
Several strategies prevent deadlocks. Lock ordering establishes a global order for acquiring multiple locks. All code that needs both locks must acquire them in the same order. If every thread acquires lock_a before lock_b, deadlock becomes impossible:
// Both threads acquire in the same orderlet handle1 = thread::spawn(move || { let _a = a1.lock().unwrap(); let _b = b1.lock().unwrap(); // Always a before b println!("Thread 1 done");});
let handle2 = thread::spawn(move || { let _a = a2.lock().unwrap(); // Always a before b let _b = b2.lock().unwrap(); println!("Thread 2 done");});Lock hierarchy formalizes lock ordering using structural relationships. If an object contains another, the outer lock is always acquired first. If objects have a natural ordering (by ID, memory address, or creation time), that order dictates lock acquisition.
Reducing lock scope minimizes the window during which deadlocks can occur. Holding a lock only while actually accessing the protected data, not during unrelated computation or I/O, reduces contention and the chance of interleaving that creates cycles.
Try-lock with backoff attempts to acquire locks without blocking. If a lock is unavailable, the thread releases held locks, waits, and retries. This approach prevents deadlock at the cost of potential livelock (threads repeatedly retrying without progress) and added complexity:
fn transfer(from: &Mutex<Account>, to: &Mutex<Account>, amount: u64) { loop { // Try to acquire both locks if let Ok(mut from_guard) = from.try_lock() { if let Ok(mut to_guard) = to.try_lock() { from_guard.balance -= amount; to_guard.balance += amount; return; // Success } // Could not get 'to', release 'from' and retry } thread::sleep(Duration::from_micros(100)); // Backoff before retry }}Lock-free data structures avoid locks entirely, using atomic operations for synchronization. The crossbeam crate provides lock-free queues, stacks, and other structures. These can eliminate certain deadlock scenarios but introduce their own complexity.
The best strategy depends on the specific situation. Simple cases benefit from lock ordering. Complex scenarios might require try-lock approaches or architectural changes that reduce shared state. Message passing, covered in the next chapter, often simplifies concurrent designs by eliminating shared mutable state entirely.
Complete example: Thread-safe cache
Combining these primitives, a thread-safe cache demonstrates the patterns in a practical context:
use std::collections::HashMap;use std::hash::Hash;use std::sync::{Arc, RwLock};use std::thread;use std::time::Duration;
pub struct Cache<K, V> { data: RwLock<HashMap<K, V>>,}
impl<K: Eq + Hash + Clone, V: Clone> Cache<K, V> { pub fn new() -> Self { Cache { data: RwLock::new(HashMap::new()), } }
pub fn get(&self, key: &K) -> Option<V> { let data = self.data.read().unwrap(); data.get(key).cloned() }
pub fn insert(&self, key: K, value: V) { let mut data = self.data.write().unwrap(); data.insert(key, value); }
pub fn get_or_insert_with<F>(&self, key: K, f: F) -> V where F: FnOnce() -> V, { // Try read lock first { let data = self.data.read().unwrap(); if let Some(value) = data.get(&key) { return value.clone(); } } // read lock released // Acquire write lock and check again (another thread may have inserted) let mut data = self.data.write().unwrap(); if let Some(value) = data.get(&key) { return value.clone(); }
// Compute and insert let value = f(); data.insert(key, value.clone()); value }}
fn main() { let cache = Arc::new(Cache::new()); let mut handles = vec![];
// Spawn threads that read and write for id in 0..4 { let cache = Arc::clone(&cache); handles.push(thread::spawn(move || { for i in 0..100 { let key = format!("key_{}", i % 20); let value = cache.get_or_insert_with(key.clone(), || { // Simulate expensive computation thread::sleep(Duration::from_micros(100)); format!("value_{}_{}", id, i) }); println!("Thread {} got: {} = {}", id, key, value); } })); }
for handle in handles { handle.join().unwrap(); }
println!("Cache size: {}", cache.data.read().unwrap().len());}The Cache uses RwLock because reads (cache hits) should vastly outnumber writes (cache misses). The get_or_insert_with method demonstrates the double-checked locking pattern: check with a read lock, upgrade to write lock only if needed, then check again because another thread might have inserted during the upgrade.
This implementation clones values on access. For expensive-to-clone types, wrapping values in Arc within the cache avoids copying data on each read. The design trade-offs depend on value size, access patterns, and performance requirements.
Atomic operations
For simple counters, flags, and other primitive values, atomic types provide lock-free synchronization. The std::sync::atomic module offers atomic versions of primitive types that can be safely shared across threads without locks:
use std::sync::atomic::{AtomicUsize, AtomicBool, Ordering};use std::sync::Arc;use std::thread;
fn main() { // Atomic counter without mutex let counter = Arc::new(AtomicUsize::new(0)); let mut handles = vec![];
for _ in 0..10 { let counter = Arc::clone(&counter); handles.push(thread::spawn(move || { for _ in 0..1000 { // fetch_add returns previous value and adds atomically counter.fetch_add(1, Ordering::SeqCst); } })); } for handle in handles { handle.join().unwrap(); }
println!("Counter: {}", counter.load(Ordering::SeqCst)); // Always 10000
// Atomic flag for signaling let running = Arc::new(AtomicBool::new(true)); let running_clone = Arc::clone(&running);
let worker = thread::spawn(move || { let mut iterations = 0; while running_clone.load(Ordering::SeqCst) { iterations += 1; thread::sleep(std::time::Duration::from_millis(10)); } println!("Worker did {} iterations", iterations); });
thread::sleep(std::time::Duration::from_millis(100)); running.store(false, Ordering::SeqCst); // Signal worker to stop worker.join().unwrap();
// Compare-and-swap for lock-free updates let value = Arc::new(AtomicUsize::new(0));
// Try to set to 42 only if current value is 0 let result = value.compare_exchange( 0, // expected current value 42, // new value if current == expected Ordering::SeqCst, // success ordering Ordering::SeqCst, // failure ordering );
match result { Ok(prev) => println!("Changed from {} to 42", prev), Err(current) => println!("Value was {}, not 0", current), }}Atomic operations are more efficient than mutexes for simple operations but require careful attention to memory ordering. Ordering::SeqCst provides the strongest guarantees and is safest for most uses. Weaker orderings offer performance benefits but require deep understanding of memory models.
Condition variables
Condition variables enable threads to wait for specific conditions without busy-waiting. A Condvar pairs with a Mutex to allow threads to sleep until signaled:
use std::sync::{Arc, Mutex, Condvar};use std::thread;use std::collections::VecDeque;
struct BoundedQueue<T> { data: Mutex<VecDeque<T>>, not_empty: Condvar, not_full: Condvar, capacity: usize,}
impl<T> BoundedQueue<T> { fn new(capacity: usize) -> Self { BoundedQueue { data: Mutex::new(VecDeque::with_capacity(capacity)), not_empty: Condvar::new(), not_full: Condvar::new(), capacity, } }
fn push(&self, item: T) { let mut data = self.data.lock().unwrap();
// Wait while queue is full while data.len() >= self.capacity { data = self.not_full.wait(data).unwrap(); }
data.push_back(item); self.not_empty.notify_one(); // Wake up one waiting consumer }
fn pop(&self) -> T { let mut data = self.data.lock().unwrap();
// Wait while queue is empty while data.is_empty() { data = self.not_empty.wait(data).unwrap(); }
let item = data.pop_front().unwrap(); self.not_full.notify_one(); // Wake up one waiting producer item }}
fn main() { let queue = Arc::new(BoundedQueue::new(5)); let mut handles = vec![];
// Producer threads for id in 0..3 { let queue = Arc::clone(&queue); handles.push(thread::spawn(move || { for i in 0..10 { queue.push(format!("item-{}-{}", id, i)); println!("Producer {} pushed item {}", id, i); } })); }
// Consumer threads for id in 0..2 { let queue = Arc::clone(&queue); handles.push(thread::spawn(move || { for _ in 0..15 { let item = queue.pop(); println!("Consumer {} got: {}", id, item); } })); }
for handle in handles { handle.join().unwrap(); }}The bounded queue blocks producers when full and consumers when empty. The wait method atomically releases the lock and sleeps until signaled. When woken, it re-acquires the lock before returning. The while loops handle spurious wakeups, checking the condition after each wake.
Scoped threads
Section titled “Scoped threads”Standard thread::spawn requires moved or ‘static data because the spawned thread might outlive its creator. Scoped threads, introduced in Rust 1.63, guarantee that spawned threads complete before the scope exits, allowing direct borrowing:
use std::thread;
fn main() { let mut data = vec![1, 2, 3, 4, 5, 6, 7, 8];
// Scoped threads can borrow from the enclosing scope // No need for Arc or move - threads guaranteed to complete before scope ends thread::scope(|s| { // Split data into chunks and process in parallel let chunk_size = data.len() / 2; let (left, right) = data.split_at_mut(chunk_size);
s.spawn(|| { for x in left.iter_mut() { *x *= 2; } });
s.spawn(|| { for x in right.iter_mut() { *x *= 2; } });
// Both threads complete before scope exits });
println!("Doubled: {:?}", data);
// Another example: collecting results from multiple threads let inputs = vec![1, 2, 3, 4, 5]; let mut results = vec![0; inputs.len()];
thread::scope(|s| { // iter_mut() hands each thread its own disjoint slot; // indexing with &mut results[i] would borrow the whole vector repeatedly for (result_slot, input) in results.iter_mut().zip(&inputs) { s.spawn(move || { // Expensive computation *result_slot = input * input; }); } });
println!("Squares: {:?}", results);}Scoped threads simplify concurrent code by eliminating Arc when data outlives the parallel computation. The scope guarantees all spawned threads complete before continuing, making the borrowing safe. This pattern is common for data-parallel operations where results collect back into the parent thread’s data structures.
Foundations Laid
Rust’s concurrency model extends ownership semantics to thread safety. The compiler prevents data races at compile time through marker traits that govern how types can be shared between threads.
Send marks types that can be safely transferred to another thread. Sync marks types whose references can be safely shared between threads. Most types derive these traits automatically; types with non-thread-safe internals do not.
Arc provides atomic reference counting for shared ownership across threads. Mutex provides mutual exclusion, allowing exactly one thread to access data at a time. Combining them as Arc<Mutex<T>> creates the standard pattern for shared mutable state.
RwLock optimizes for read-heavy workloads by allowing multiple readers or a single writer. The choice between Mutex and RwLock depends on access patterns and critical section length.
Deadlocks remain possible despite Rust’s safety guarantees. Lock ordering, reduced lock scope, and try-lock with backoff are strategies for prevention. Architectural choices that minimize shared mutable state often prove more effective than complex locking protocols.
The next chapter explores message passing, where threads communicate by sending data through channels rather than sharing state directly. This approach often simplifies concurrent designs and aligns naturally with Rust’s ownership model.