Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Concurrent Containers

Rust feature concurrent (see Installation). The module uses core atomics and alloc; it does not need std.

Model: Grow Shared, Shrink Exclusive

Shared access (&self) may install pages and recycle slots. Allocated pages and directory chunks stay at stable addresses until exclusive access (&mut self) or destruction, so memory reclamation needs no epochs or hazard pointers. Removal of pages, conversion to plain types and shrink_to_fit need &mut self.

Example

use paged_collections::concurrent::{ConcurrentAppendHive, ConcurrentSparseSet};

// ANCHOR: queue
fn fifo_example() {
    use paged_collections::concurrent::ConcurrentQueue;

    let queue = ConcurrentQueue::<_, 2>::new();
    queue.push("first");
    queue.push("second");
    assert_eq!(queue.pop(), Some("first"));
    assert_eq!(queue.pop(), Some("second"));
}
// ANCHOR_END: queue

// ANCHOR: priority_queue
fn priority_example() {
    use paged_collections::concurrent::ConcurrentPriorityQueue;

    let queue = ConcurrentPriorityQueue::<u32, i32, 4>::with_shards(3);
    queue.push(1, 10);
    queue.push(5, 20);
    assert_eq!(queue.change_priority(&1, 30), Some(10));
    assert_eq!(queue.pop_exact(), Some((1, 30)));
    assert_eq!(queue.pop(), Some((5, 20)));
}
// ANCHOR_END: priority_queue

fn main() {
    fifo_example();
    priority_example();
    let hive: ConcurrentAppendHive<usize> = ConcurrentAppendHive::new();
    let keys: ConcurrentSparseSet<usize> = ConcurrentSparseSet::new();
    std::thread::scope(|scope| {
        for worker in 0..4 {
            let (hive, keys) = (&hive, &keys);
            scope.spawn(move || {
                for value in worker * 4..(worker + 1) * 4 {
                    hive.insert(value);
                    keys.insert(value);
                }
            });
        }
    });
    println!("hive count = {}", hive.len());
    println!("set count = {}", keys.len());
    let mut values: Vec<_> = hive.into_hive().values().copied().collect();
    values.sort_unstable();
    let mut contents: Vec<_> = keys.iter().copied().collect();
    contents.sort_unstable();
    println!("hive values = {values:?}");
    println!("set keys = {contents:?}");
}
hive count = 16
set count = 16
hive values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
set keys = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

Containers

TypeShared (&self)Exclusive (&mut self)Lookups return
ConcurrentHive<T>insert, remove, takeiteration with &mut, drain, shrink_to_fit, into_hiveRef guard (two atomic writes per lookup)
ConcurrentAppendHive<T>insertremove, mutable access, shrink_to_fit, into_hive&T (one Acquire load)
ConcurrentPagedVec<T>pushremoval, editing, shrink_to_fit, conversion&T
ConcurrentQueue<T> (Python ConcurrentQueue)push, popclear, drain, shrink_to_fitowned value from pop
ConcurrentPriorityQueue<K, P> (Python ConcurrentPriorityQueue, ConcurrentPriorityQueueF64)push, change priority, remove, popclear, drain, shrink_to_fitcloned priority or closure
ConcurrentSparseSet<K>, ConcurrentSparseMap<K, V>insertremoval, clear, drain, shrink_to_fit, conversion&K, &V
ConcurrentDirectMap<K, V>insert, replace, remove, entry (per-page RwLock)drain, shrink_to_fit, reset, into_innerclosures (with), clones (get_cloned), entry guards
AtomicDirectMap (usize -> u64)lock-free insert, update, removeshrink_to_fitcopied u64
AtomicIdMap (Id -> u32)lock-free insert, update, removeshrink_to_fitcopied u32
ConcurrentIdAllocatorallocate, free, occupant, iterclearcopied Id

Notes per type:

  • ConcurrentHive: a lookup guard pins its value until dropped; hot values contend even between readers. Prefer the plain Hive when shared mutation is not needed.
  • ConcurrentAppendHive: iteration may miss insertions in flight. From<Hive> and into_hive keep live ids and stale-id history, in O(index bound).
  • Sparse set and map: entries cannot be removed or changed while shared. shrink_to_fit frees index pages with no entry and dense pages beyond the last entry; stored entries keep their addresses. Inserts of the same slot wait for its writer; other slots proceed independently. An occupied slot refuses other generations. Each try_insert reserves a dense position from one shared counter; under contention use try_insert_many, which reserves once per batch. extend and collect keep the first occupant of each slot, including existing occupants when extending. drain yields owned items in dense order and keeps allocated pages for reuse.
  • ConcurrentDirectMap: neighbouring keys share a page lock and contend. Release guards and entries before locking the same page again. Ordered shared traversals are consistent per page only. drain yields owned entries in key-index order and keeps allocated pages for reuse.
  • AtomicDirectMap, AtomicIdMap: prefer them over ConcurrentDirectMap when values fit: u64 values below u64::MAX, or any u32 value keyed by Id. Traversals copy values in index order.

The direct map and both atomic maps release empty pages with shrink_to_fit. Flat directory chunks stay allocated. Radix collapses branches with only one remaining child. Shared insertion can reinstall released pages.

Use for item in &collection on containers with iter and for item in &mut collection on containers with iter_mut. These loops use the same item types, order and consistency as the respective iterator methods.

ConcurrentPagedVec

Concurrent pushes can finish out of order. A point lookup can read a published element beyond the first pending slot. Length, iteration and page slices all use the contiguous published prefix.

Slots 0 and 1 are published while slot 2 is pending. Slot 3 already contains D. The length is 2, but get(3) can read D.
When slot 2 finishes publishing, the visible prefix can advance through slot 3. An iterator created earlier retains the prefix it started with.

shrink_to_fit frees pages wholly beyond the vector’s length.

ConcurrentQueue

ConcurrentQueue is an unbounded multi-producer, multi-consumer FIFO queue, adapted from Crossbeam’s SegQueue. It recycles pages through a free stack and waits at page boundaries. A pop can also wait for a push that has claimed a slot to publish its value. Shared peeking, iteration, cloning, snapshots and serialization are unavailable; an owned queue can be converted to a PagedDeque for serialization. The Python ConcurrentQueue holds Python objects and drains into a list. See Python Threads and the Python FIFO benchmarks.

A pop takes A from the head page. A push writes E into the next free slot after D on the tail page.
Producers claim slots at the tail and consumers take them from the head. A drained head page can be recycled for future pushes.
#![allow(unused)]
fn main() {
fn fifo_example() {
    use paged_collections::concurrent::ConcurrentQueue;

    let queue = ConcurrentQueue::<_, 2>::new();
    queue.push("first");
    queue.push("second");
    assert_eq!(queue.pop(), Some("first"));
    assert_eq!(queue.pop(), Some("second"));
}
}

ConcurrentPriorityQueue

ConcurrentPriorityQueue is an indexed max-priority queue split into shards by key page. Its pop is relaxed: it chooses the greatest of up to two sampled shard tops, with a fallback scan, and does not guarantee the global maximum. Use pop_exact to select the global maximum. Per-key operations lock one shard; pop_exact locks all shards. Callbacks and user trait implementations run under shard locks and must not call back into the same queue. The Python classes ConcurrentPriorityQueue and ConcurrentPriorityQueueF64 store numeric priorities and also support min queues. See Python Threads and the Python priority-queue benchmarks.

Four shard tops have priorities 45, 70, 95, and 35. A pop that samples the first two takes 70. An exact pop from the same state takes 95.
In this max-queue, the sampled shards determine which entry pop returns. pop_exact locks all shards and selects the global maximum.
#![allow(unused)]
fn main() {
fn priority_example() {
    use paged_collections::concurrent::ConcurrentPriorityQueue;

    let queue = ConcurrentPriorityQueue::<u32, i32, 4>::with_shards(3);
    queue.push(1, 10);
    queue.push(5, 20);
    assert_eq!(queue.change_priority(&1, 30), Some(10));
    assert_eq!(queue.pop_exact(), Some((1, 30)));
    assert_eq!(queue.pop(), Some((5, 20)));
}
}

Directories

The sparse types, ConcurrentDirectMap and AtomicDirectMap take a SharedDirectory parameter: Flat (default; O(1) page lookup, finite index range) or Radix (any usize index, memory proportional to installed pages, O(depth) lookup). AtomicIdMap is Flat-only; Tree has no concurrent form.

Id Allocation Under Contention

With std, freed slots go to one of 32 per-thread shards (no_std builds use one shared stack), each with its own free stack and block of fresh indices; a thread steals from other shards only when its own is empty. A single-threaded caller takes an inline fast path. Measured scaling is in Benchmarks.

occupant(index) reads the live generation at one index. Iterating over &allocator scans live ids in index order up to the bound read at the start. The scan takes no snapshot. Allocations and frees during iteration may or may not be reflected, and a yielded id can already have been freed.

Element Invariance

Shared insertion requires every element type to be invariant: shortening a stored reference’s lifetime would let a shorter-lived reference be inserted while the owner still expects 'static. The containers are invariant in their element types; compile-fail tests check this for each type.

Without std

Under no_std, the per-page locks of ConcurrentDirectMap spin. Lock guards are !Send there.

API: concurrent.