Concurrent Data Structures
local graph
Chapter 21 — Concurrent Data Structures
Section titled “Chapter 21 — Concurrent Data Structures”Simul et singulis. (Together and individually.)
The synchronization primitives covered so far, mutexes and read-write locks, protect data by serializing access. When one thread holds a lock, others wait. This approach works and has the advantage of familiarity: wrap data in a mutex, acquire before access, release when done. The pattern scales to complex data structures without requiring those structures to know anything about concurrency. A Mutex<HashMap<K, V>> makes any HashMap thread-safe.
The cost is contention. Under high concurrency, threads spend significant time waiting for locks rather than doing useful work. A mutex protecting a hot data structure becomes a bottleneck. Even read-write locks, which allow concurrent readers, serialize all writers and block readers during writes. When access patterns involve frequent modifications or when latency matters more than throughput, lock-based approaches show their limits.
Lock-free data structures take a different approach. Rather than mutual exclusion, they use atomic operations to ensure consistency. Multiple threads can operate on the data structure simultaneously, making progress independently. No thread waits for another to release a lock because there are no locks. The trade-off shifts: simpler access patterns (no deadlocks, no priority inversion, bounded worst-case latency) in exchange for more complex implementation and sometimes weaker ordering guarantees.
OOP languages provide concurrent collections in their standard libraries: Java’s ConcurrentHashMap, C#‘s ConcurrentDictionary, various blocking queues and concurrent sets. These abstractions hide the complexity of lock-free algorithms behind familiar interfaces. Rust takes a more minimal approach in its standard library, providing atomic primitives but leaving concurrent collections to the ecosystem. The crossbeam family of crates fills this gap with thoroughly tested, high-performance concurrent data structures.
Atomic operations: the foundation
Lock-free algorithms build on atomic operations, indivisible read-modify-write operations that the hardware guarantees complete without interruption. Rust exposes these through the std::sync::atomic module, providing atomic versions of primitive types: AtomicBool, AtomicI32, AtomicUsize, AtomicPtr, and others.
The fundamental operations on atomic types go beyond load and store. Compare-and-swap (CAS), exposed as compare_exchange, attempts to update a value only if it currently matches an expected value. If the current value matches, the update succeeds atomically. If it differs (another thread modified it first), the operation fails and returns the current value. CAS enables optimistic concurrency: assume no conflict, attempt the update, retry if another thread interfered.
Consider implementing an atomic counter without locks. A naive increment would read the value, add one, and store the result. Between the read and store, another thread could modify the value, losing its update. CAS solves this:
use std::sync::atomic::{AtomicU64, Ordering};
struct AtomicCounter { value: AtomicU64,}impl AtomicCounter { fn new() -> Self { AtomicCounter { value: AtomicU64::new(0), } }
fn increment(&self) -> u64 { self.value.fetch_add(1, Ordering::SeqCst) }
fn get(&self) -> u64 { self.value.load(Ordering::SeqCst) }}The fetch_add method performs an atomic increment, returning the previous value. No lock is needed. Multiple threads can increment simultaneously, and no updates are lost. The hardware ensures atomicity through processor-specific mechanisms (locked instructions on x86, load-linked/store-conditional on ARM).
The Ordering parameter specifies memory ordering constraints: how this operation relates to other memory operations. SeqCst (sequentially consistent) provides the strongest guarantees, establishing a single global order that all threads agree on. Weaker orderings like Relaxed, Acquire, and Release allow more optimization but require careful reasoning about memory visibility. For most application code, SeqCst is the safest default. The performance difference often matters less than correctness, and subtle ordering bugs are notoriously difficult to diagnose.
Atomic pointers enable more complex lock-free structures. An AtomicPtr<T> holds a pointer that can be atomically loaded, stored, or swapped. Lock-free linked lists, stacks, and queues use atomic
pointers to manage node references without locks:
use std::sync::atomic::{AtomicPtr, Ordering};use std::ptr;
struct Node<T> { data: T, next: AtomicPtr<Node<T>>,}
struct LockFreeStack<T> { head: AtomicPtr<Node<T>>,}
impl<T> LockFreeStack<T> { fn new() -> Self { LockFreeStack { head: AtomicPtr::new(ptr::null_mut()), } }
fn push(&self, data: T) { let new_node = Box::into_raw(Box::new(Node { data, next: AtomicPtr::new(ptr::null_mut()), }));
loop { let old_head = self.head.load(Ordering::Acquire); unsafe { (*new_node).next.store(old_head, Ordering::Relaxed) };
match self.head.compare_exchange( old_head, new_node, Ordering::Release, Ordering::Relaxed, ) { Ok(_) => break, Err(_) => continue, // Another thread modified head, retry } } }}This stack allows concurrent pushes without locks. Each push reads the current head, links the new node to it, then attempts to swing the head to the new node. If another thread pushed concurrently, compare_exchange fails and the operation retries with the updated head.
Lock-free implementations are subtle. The stack above handles push correctly but pop requires careful handling of memory reclamation (when can a popped node be freed if another thread might be reading it?). This complexity motivates using well-tested libraries rather than writing lock-free code from scratch.
Crossbeam: battle-tested concurrent primitives
The crossbeam crate family provides concurrent data structures and synchronization primitives that have undergone extensive testing and optimization. Rather than implementing lock-free algorithms yourself, which is error-prone even for experts, crossbeam offers production-ready implementations.
Crossbeam divides into several crates, each focused on specific functionality. The crossbeam-channel crate provides multi-producer, multi-consumer channels with better performance than the standard library’s mpsc. The crossbeam-deque crate offers work-stealing deques for task scheduling. The crossbeam-queue crate provides lock-free queues. The crossbeam-epoch crate implements epoch-based memory reclamation, solving the thorny problem of when to free memory in lock-free structures.
The umbrella crossbeam crate re-exports these components for convenience:
use crossbeam::channel::{bounded, unbounded, Sender, Receiver};use crossbeam::deque::{Worker, Stealer};use crossbeam::queue::ArrayQueue;Crossbeam channels improve on the standard library in several ways. They support multiple consumers (the standard mpsc only supports a single consumer). They offer both bounded and unbounded variants with different backpressure behaviors. They integrate with the select! macro for waiting on multiple channels. Performance is generally better due to careful optimization.
The bounded channel constructor takes a capacity and returns a sender-receiver pair:
use crossbeam::channel::bounded;
fn producer_consumer_example() { let (tx, rx) = bounded::<u64>(100);
// Multiple producers for id in 0..4 { let tx = tx.clone(); std::thread::spawn(move || { for i in 0..1000 { tx.send(id * 1000 + i).unwrap(); } }); }
// Multiple consumers for _ in 0..2 { let rx = rx.clone(); std::thread::spawn(move || { while let Ok(item) = rx.recv() { process(item); } }); }}Unlike std::sync::mpsc::Receiver, crossbeam’s receiver implements Clone. Multiple threads can receive from the same channel, with each message going to exactly one receiver. This multi-producer, multi-consumer (MPMC) pattern enables load balancing across worker threads without additional coordination.
Lock-free queues
Crossbeam’s ArrayQueue provides a bounded, lock-free queue with fixed capacity. Push and pop operations complete without blocking on locks, making the queue suitable for scenarios where latency predictability matters:
use crossbeam::queue::ArrayQueue;use std::sync::Arc;
fn array_queue_example() { let queue = Arc::new(ArrayQueue::<WorkItem>::new(1024));
// Producer let q = Arc::clone(&queue); std::thread::spawn(move || { for item in generate_work() { while q.push(item.clone()).is_err() { std::thread::yield_now(); // Queue full, back off } } });
// Consumer let q = Arc::clone(&queue); std::thread::spawn(move || { loop { match q.pop() { Some(item) => process(item), None => std::thread::yield_now(), // Queue empty } } });}The push method returns an error if the queue is full rather than blocking. The caller decides how to handle backpressure: spin, yield, sleep, or drop the item. This non-blocking behavior differs from channels, which can block on a full bounded channel.
SegQueue provides an unbounded lock-free queue that grows dynamically:
use crossbeam::queue::SegQueue;
let queue: SegQueue<Task> = SegQueue::new();
// Push never blocks or fails (absent memory exhaustion)queue.push(task);
// Pop returns None if emptyif let Some(task) = queue.pop() { execute(task);}The unbounded nature means producers never block, which can be advantageous when producers should not wait on consumers. The trade-off is memory growth: if consumers fall behind, the queue grows without bound. Careful system design ensures consumers keep pace or implements separate flow control.
Work-stealing deques
Parallel computation often involves splitting work into tasks, distributing those tasks across worker threads, and collecting results. A naive approach assigns tasks to workers statically, but workload imbalance leaves some workers idle while others are overloaded. Work stealing addresses this by allowing idle workers to steal tasks from busy workers.
Crossbeam’s crossbeam-deque implements work-stealing deques. Each worker has a deque (double-ended queue) for its tasks. Workers push and pop from one end (LIFO, last-in-first-out), while other workers steal from the opposite end (FIFO, first-in-first-out). This asymmetry has useful properties: workers tend to work on their own recently-created tasks (good for cache locality), while stolen tasks are older, often representing independent subtrees of work.
The following diagram illustrates work-stealing in action:
graph LR
subgraph W2["Worker 2"]
D2["Deque: T4"]
end
subgraph W1["Worker 1"]
D1["Deque: T1, T2, T3"]
end
subgraph W3["Worker 3 (idle)"]
D3["Deque: empty"]
end
D1 -- "steals T1" --> D3
[!visual-conversion] An idle worker steals from a busy worker’s deque. Print diagram (PDF 550, printed p. 540) recreated in Mermaid; labels verbatim. (Worker 2 stands alone above the other two in print, with no edge.)
Setting up work-stealing requires creating worker-stealer pairs:
use crossbeam::deque::{Worker, Stealer};
fn parallel_work() { // Create worker deques let worker1 = Worker::<Task>::new_fifo(); let worker2 = Worker::<Task>::new_fifo();
// Get stealers that other workers can use let stealer1 = worker1.stealer(); let stealer2 = worker2.stealer();
// Worker 1 adds its own tasks and can steal from worker 2 let stealers_for_1 = vec![stealer2.clone()];
// Worker 2 adds its own tasks and can steal from worker 1 let stealers_for_2 = vec![stealer1.clone()];
// Spawn worker threads std::thread::spawn(move || { run_worker(worker1, stealers_for_1); });
std::thread::spawn(move || { run_worker(worker2, stealers_for_2); });}
fn run_worker(worker: Worker<Task>, stealers: Vec<Stealer<Task>>) { loop { // Try own deque first if let Some(task) = worker.pop() { execute(task, &worker); continue; }
// Own deque empty, try stealing for stealer in &stealers { if let crossbeam::deque::Steal::Success(task) = stealer.steal() { execute(task, &worker); break; } } }}The Worker type provides push and pop for the owning thread. The Stealer type, obtained from worker.stealer(), provides steal for other threads. The separation enforces that only the owner pushes and pops normally, while stealing is the only cross-thread operation.
Work stealing shines for divide-and-conquer algorithms. A task spawns subtasks by pushing them to the local deque. If the worker completes before subtasks do, it works on those subtasks directly. If the worker is busy, other workers steal subtasks. The approach adapts naturally to varying task granularity and processor availability.
Libraries like rayon build on work-stealing to provide parallel iterators. When you call par_iter() on a collection, rayon uses work-stealing behind the scenes to distribute iteration across threads:
use rayon::prelude::*;
let results: Vec<Output> = inputs .par_iter() .map(|input| expensive_computation(input)) .collect();Rayon handles the complexity of work distribution, stealing, and load balancing. Understanding that work-stealing underlies this abstraction helps when tuning parallel code or understanding its performance characteristics.
Epoch-based reclamation
Lock-free data structures face a subtle problem: when is it safe to free memory? Consider a lock-free linked list. One thread traverses nodes, following pointers. Another thread removes a node and wants to free its memory. If the first thread is mid-traversal, reading the node about to be freed, freeing the memory causes undefined behavior.
Locks avoid this by preventing concurrent access during modifications. Without locks, determining when memory is safe to free requires alternative mechanisms. Epoch-based reclamation, provided by crossbeam-epoch, is one solution.
The idea divides time into epochs. Threads announce when they enter and leave critical sections. Memory retired during an epoch cannot be freed until all threads have left that epoch. Once all threads have advanced past the epoch when memory was retired, no thread can possibly hold a reference to that memory, and freeing is safe.
Crossbeam’s epoch API uses guards to mark critical sections:
use crossbeam::epoch::{self, Atomic, Owned, Shared};use std::sync::atomic::Ordering;
struct Node { data: u64, next: Atomic<Node>,}
fn traverse_list(head: &Atomic<Node>) { // Pin the current thread, preventing epoch advancement let guard = epoch::pin();
let mut current = head.load(Ordering::Acquire, &guard); while !current.is_null() { let node = unsafe { current.deref() }; println!("Data: {}", node.data); current = node.next.load(Ordering::Acquire, &guard); }
// Guard drops here, unpinning the thread}The guard pins the current thread to the current epoch. While pinned, no memory retired by other threads will be freed. This guarantees that pointers loaded during the traversal remain valid. When the guard drops, the thread unpins, allowing epochs to advance.
Retiring memory for later reclamation uses the guard:
fn remove_node(prev: &Atomic<Node>, target: Shared<Node>, guard: &epoch::Guard) { let target_node = unsafe { target.deref() }; let next = target_node.next.load(Ordering::Acquire, guard);
// Unlink the target node prev.compare_exchange(target, next, Ordering::Release, Ordering::Relaxed, guard);
// Retire the removed node unsafe { guard.defer_destroy(target); }}The defer_destroy method schedules the node for destruction once it is safe. The actual destruction happens later, after sufficient epochs pass. The memory is not freed immediately, which delays reclamation, but this delay ensures safety.
Epoch-based reclamation is not suitable for all scenarios. Long-running pinned critical sections can delay memory reclamation indefinitely. Real-time systems with strict memory bounds may need alternative approaches. But for many concurrent data structures, epoch reclamation provides a practical balance between safety and performance.
Concurrent hash maps
High-performance concurrent hash maps appear frequently in server applications: caching, rate limiting, session storage, connection tracking. The standard library’s HashMap wrapped in RwLock works but creates contention when many threads access the map concurrently.
The dashmap crate provides a concurrent hash map optimized for high-concurrency scenarios. Rather than a single lock, it uses sharding: the map is divided into segments, each with its own lock. Operations on different segments proceed in parallel:
use dashmap::DashMap;use std::sync::Arc;
fn concurrent_cache_example() { let cache: Arc<DashMap<String, ComputedValue>> = Arc::new(DashMap::new());
// Multiple threads read and write concurrently let handles: Vec<_> = (0..8) .map(|id| { let cache = Arc::clone(&cache); std::thread::spawn(move || { for i in 0..1000 { let key = format!("key_{}", i % 100);
// Try to get existing value if let Some(value) = cache.get(&key) { use_value(&*value); continue; }
// Compute and insert let value = expensive_computation(&key); cache.insert(key, value); } }) }) .collect();
for handle in handles { handle.join().unwrap(); }}The API resembles HashMap but methods that would return references instead return guards that manage access. The get method returns an Option<Ref<K, V>>, a guard that dereferences to the value while preventing structural modifications to that segment.
DashMap also provides entry API for atomic get-or-insert operations:
let value = cache.entry(key.clone()).or_insert_with(|| { expensive_computation(&key)});The entry API ensures that the computation runs at most once for a given key, even under concurrent access. Without this, multiple threads might compute the value simultaneously, wasting resources.
Other concurrent map implementations exist with different trade-offs. flurry ports Java’s ConcurrentHashMap algorithm to Rust. scc (Scalable Concurrent Containers) provides hash maps optimized for read-heavy or write-heavy workloads. The choice depends on access patterns, key-value sizes, and specific performance requirements.
When to use what
The variety of concurrent data structures reflects the variety of concurrent programming needs. No single structure is universally best. The choice depends on access patterns, performance requirements, and complexity tolerance.
Lock-based structures (Mutex<T>, RwLock<T>) suit most cases. They are straightforward to reason about, work with any inner type, and often perform well enough. When contention is low, the overhead of locking is minimal. When code complexity matters more than maximizing throughput, lock-based approaches win on clarity.
Concurrent channels suit producer-consumer patterns where threads communicate by passing messages. Crossbeam channels handle multiple producers and consumers efficiently. They decouple producers from consumers, simplifying system design. When the natural model is message passing rather than shared state, channels are the appropriate choice.
Lock-free queues suit scenarios requiring predictable latency. Where a mutex might occasionally cause a thread to wait, lock-free operations complete in bounded time. Real-time systems, high-frequency trading, and other latency-sensitive applications benefit from this predictability.
Work-stealing deques suit parallel computation with dynamic task generation. Divide-and-conquer algorithms, graph traversal, and tree processing all fit this pattern. Rather than implementing work-stealing yourself, consider rayon for parallel iteration or tokio for async task scheduling.
Concurrent hash maps suit shared caches and lookups under high concurrency. When many threads access a map and contention on a single lock becomes a bottleneck, sharded maps like dashmap reduce contention at the cost of more complex iteration semantics.
The following diagram summarizes the decision process:
graph TD
S(["Shared Mutable State?"]) --> L{"Latency-critical?"}
L -- Yes --> LF["Lock-Free Structures<br/>(crossbeam queues)"]
L -- No --> H{"High contention on map?"}
H -- Yes --> CC["Concurrent Collections<br/>(dashmap, flurry)"]
H -- No --> P{"Producer-consumer?"}
P -- Yes --> CH["Channels<br/>(crossbeam-channel)"]
P -- No --> PC{"Parallel computation?"}
PC -- Yes --> WS["Work-Stealing<br/>(rayon, crossbeam-deque)"]
PC -- No --> MX["Mutex / RwLock<br/>(std::sync)"]
[!visual-conversion] Choosing the appropriate concurrent data structure. Print flowchart (PDF 558, printed p. 548) recreated in Mermaid; decision diamonds, Yes/No branches and labels verbatim.
In my experience, starting with lock-based structures and migrating to specialized structures when profiling reveals contention is a sound strategy. Premature optimization toward lock-free structures adds complexity without guaranteed benefit. When benchmarks show that locking is the bottleneck, and not some other aspect of the system, then the migration to concurrent collections or lock-free structures is justified.
Complete example: parallel web crawler
The following example combines several concurrent data structures in a parallel web crawler. It uses channels for task distribution, a concurrent set for tracking visited URLs, and work-stealing semantics through multiple consumer threads:
use crossbeam::channel::{bounded, Sender, Receiver};use dashmap::DashSet;use std::sync::Arc;use std::thread;use std::time::Duration;
struct CrawlTask { url: String, depth: u32,}
struct Crawler { visited: Arc<DashSet<String>>, max_depth: u32, task_tx: Sender<CrawlTask>, task_rx: Receiver<CrawlTask>,}
impl Crawler { fn new(max_depth: u32, queue_size: usize) -> Self { let (task_tx, task_rx) = bounded(queue_size); Crawler { visited: Arc::new(DashSet::new()), max_depth, task_tx, task_rx, } }
fn crawl(&self, start_url: String, num_workers: usize) { // Seed with initial URL self.task_tx .send(CrawlTask { url: start_url, depth: 0, }) .unwrap();
let mut handles = Vec::new();
// Spawn worker threads for id in 0..num_workers { let visited = Arc::clone(&self.visited); let task_rx = self.task_rx.clone(); let task_tx = self.task_tx.clone(); let max_depth = self.max_depth;
handles.push(thread::spawn(move || { while let Ok(task) = task_rx.recv_timeout(Duration::from_secs(2)) { // Skip if already visited if !visited.insert(task.url.clone()) { continue; }
println!("Worker {} crawling: {}", id, task.url);
// Simulate fetching and parsing let links = fetch_and_parse(&task.url);
// Queue discovered links if task.depth < max_depth { for link in links { let _ = task_tx.try_send(CrawlTask { url: link, depth: task.depth + 1, }); } } } println!("Worker {} finished", id); })); }
// Workers exit once the queue has stayed empty for 2 seconds // (recv_timeout); self still holds a sender, so the channel never closes
for handle in handles { handle.join().unwrap(); }
println!("Crawled {} unique URLs", self.visited.len()); }}
fn fetch_and_parse(url: &str) -> Vec<String> { // Simulate network latency thread::sleep(Duration::from_millis(50));
// Return mock discovered links vec![ format!("{}/page1", url), format!("{}/page2", url), format!("{}/page3", url), ]}
fn main() { let crawler = Crawler::new(2, 100); crawler.crawl("https://example.com".to_string(), 4);}The crawler demonstrates several patterns working together. The DashSet tracks visited URLs, allowing concurrent insert-and-check operations. The bounded channel distributes work to multiple consumers. Workers use recv_timeout to detect when the queue has been empty long enough to suggest completion. The try_send for new tasks avoids blocking if the queue is full, dropping excess work rather than slowing down workers.
This structure handles the dynamic nature of web crawling: the number of discovered URLs is unpredictable, processing time varies per page, and work distribution must adapt to what each page contains. The concurrent primitives handle coordination; the application logic focuses on crawling semantics.
Structures Surveyed
Concurrent data structures provide thread-safe access without
requiring callers to manage synchronization. Lock-based wrappers
like Mutex<T> work for any type but serialize access. Lock-free
structures allow concurrent operations without mutual exclusion,
trading implementation complexity for reduced contention.
Atomic operations form the foundation of lock-free programming. Compare-and-swap enables optimistic updates that retry on conflict. Memory ordering constraints control visibility across threads; SeqCst provides strong guarantees at potential performance cost.
Crossbeam provides production-ready concurrent primitives. Its channels support multiple producers and consumers. ArrayQueue and SegQueue offer lock-free queue implementations. Work-stealing deques enable efficient parallel task distribution. Epoch-based reclamation solves the memory safety problem inherent in lock-free structures.
Concurrent hash maps from crates like dashmap reduce contention through sharding. Multiple segments with independent locks allow parallel access to different parts of the map.
Choosing the right structure depends on access patterns. Start with lock-based approaches for simplicity. Move to specialized structures when profiling identifies contention as a bottleneck. Lock-free structures offer latency predictability at the cost of complexity. Work-stealing suits dynamic parallel workloads. Channels simplify producer-consumer designs.
The next chapter examines testing strategies, exploring how Rust’s type system, ownership model, and built-in test framework enable comprehensive testing from unit tests through integration tests to property-based testing.