docs

#2.16. sync - Concurrency primitives

On this page

The core::sync module defines the primitive traits and types for safe access to shared state. They are used to share data between multiple tasks or threads under Nabi's GC and M:N scheduler.

Atomic, Mutex, RwLock and Cell are in the prelude and usable without any import; the ordering enums (LoadOrdering, StoreOrdering, UpdateOrdering) are not, but their variants resolve from the parameter type (x.load(SeqCst)). Where concurrent code should be visibly marked as such, a narrow import like the following is recommended.

nabi
use core::sync::{Atomic, Mutex, RwLock, Once, Condvar, Cell};

#2.16.1. Overview of the primitives

Each primitive covers a different concurrency scenario. The following table summarizes each type's meaning and where it fits.

TypeMeaningWhere used
Atomic<T>lock-free atomic operations (T = primitive)counter, flag, sequence number
Mutex<T>exclusive lock (single writer)shared mutable state
RwLock<T>multiple readers or a single writerread-heavy state
Cell<T>thread-local interior mutability (no lock)single-threaded mutable
Onceruns an initializer exactly once (2.16.4a)lazy global setup
Condvarwaits for a condition under a Mutex (2.16.4a)producer / consumer
Frozen<T>read-only sharing of a copied value (2.16.4b)shared configuration
FrozenList<T>, FrozenDict<K, V>a collection no one changes, shared with no copy (2.9.7b)tables, read-mostly maps

#2.16.2. Atomic<T> - lock-free atomics

Atomic<T> is the lightest primitive. Internally it is implemented with per-T atomic instructions and has the following shape.

wait may return spuriously, so the caller re-checks the condition (futex semantics).

store is an atomic store, not a swap. compare_exchange_weak never fails spuriously in this implementation; it behaves as compare_exchange. PartialEq is required because compare_exchange compares the old value with current; Ptr<T> compares by address.

#LoadOrdering, StoreOrdering, UpdateOrdering

Atomic operations come in five memory-ordering strengths. Each kind of operation has its own ordering type, which holds only the orderings it can take, so an invalid ordering is a compile error rather than a runtime check (Swift Atomics' split).

nabi
enum LoadOrdering   { Relaxed, Acquire, SeqCst }                     // load; a failed compare-exchange
enum StoreOrdering  { Relaxed, Release, SeqCst }                     // store
enum UpdateOrdering { Relaxed, Acquire, Release, AcqRel, SeqCst }    // swap, fetch_*, a compare-exchange that succeeds
OrderingMeaning
Relaxedno synchronization (counters etc.)
Acquiresynchronization guaranteed after the load
Releasesynchronization guaranteed before the store
AcqRelboth directions for a read-modify-write
SeqCstglobal sequential consistency (default, safe)

The orderings have their C++20 meaning; the memory model they belong to (happens-before, which library operations synchronize, data races) is refs-lang 7.9. The default is the safe SeqCst. A load cannot release and a store cannot acquire: a.store(x, Acquire) is a compile error (StoreOrdering has no Acquire; a store takes Relaxed, Release or SeqCst). The failure ordering of a compare-exchange is a load ordering. The variants are written without a prefix: the parameter's type picks the enum (refs-lang 2.4.8). The three types are not in the prelude, and their names do not clash with the comparison cmp::Ordering. The ordering argument must be a compile-time constant. Weak orderings should be used carefully and only where performance is critical.

#Example

The most common use, incrementing a counter, is written as follows.

nabi
static COUNTER: Atomic<i32> = Atomic::new(0);

task::spawn(async { COUNTER.fetch_add(1, Relaxed); });
task::spawn(async { COUNTER.fetch_add(1, Relaxed); });
// result: COUNTER == 2 (no race)

let v = COUNTER.load(SeqCst);     //→ 2

#CAS (compare-and-swap)

Updates that atomics do not offer directly are built on compare-and-swap loops. The following keeps the largest value ever stored.

nabi
fn store_max(cell: Atomic<i64>, x: i64) {
    let cur = cell.load(Acquire);
    loop {
        if cur >= x { break; }
        match cell.compare_exchange(cur, x, AcqRel, Acquire) {
            Ok(_)       => break,
            Err(actual) => cur = actual,          // another task got there first; retry with its value
        }
    }
}

The element type must be an AtomicPrimitive: a collection such as List<T> cannot be held in an Atomic. The trait is sealed (refs-lang 6.2.15): the types above are all of its impls, and an impl AtomicPrimitive in another package is an error. Shared collections go in a Mutex<T> (2.16.3).

#2.16.3. Mutex<T> - exclusive lock

Shared state that is hard to express with atomics alone uses Mutex<T>. Internally it consists of a futex and the payload; a guard bound with using releases the lock.

A guard does not forward the methods of the value it protects: g.push(1) on a MutexGuard<List<i32>> is an error. Reach the value through get, set and update.

m.with(f) locks, calls f with the protected value and unlocks when f returns, returning its result: log.with(|v| v.push(x)), let n = log.with(|v| v.len()). The value is lent to f like get()'s view, under the rules of ThreadLocal::with: it may not leave f (returned, stored, sent, kept by a callee or a closure), so f is not async (E0136); return a copy (.clone()) or what is computed from it. Keep the guard (using g = m.lock()) to hold the lock across statements or an await. RwLock::read_with(f) and write_with(f) are the same under the read and write lock.

#Example

A guard bound with using is dropped on leaving the block, releasing the lock. A guard received without using is not released automatically, so it must always be bound with using. A guard is received from a call, a method call or await. A received guard may only initialize a binding (let, a pattern, using), be assigned to a variable, or be handed to the caller (return, the function's value). Passing it to a function, calling a method on it, storing it in a field or a collection, or discarding it is a compile error. A guard bound with using may be passed to functions; a guard bound without using is not released by passing it on. Binding a guard with a plain let (or if let) that is never released by using, or discarding a guard returned by lock, is a compile error.

Mutex::new(value) takes value over: using the caller's handle afterwards is a compile error, and so is using what get returned or set gave after the guard's using block ends, handing over what get returned while the guard holds it (until set gives the lock a new value), or returning it, yielding it, making it the block's value or giving it to a coroutine run after the block (2.13.9). So is throwing an error that holds it (throw Leak { xs: g.get() };): the catcher runs after the lock is released. What get returns is a scoped view: like the guard it is neither Send nor Sync, and passing it to a callee that keeps it (stores it in a Cell, a field, a capture, a thread-local) is compile error E0106 at the call, whose help names get_clone(). get_clone() returns a deep copy (T: Clone), which is free to outlive the lock. Work on the view inside the using block, or keep a get_clone(). A guard is !Sync and good only inside its using block: using a copy of it (in a collection, a closure, a field) after the block ends is a compile error; to use the value in a closure that runs on another thread, take a deep copy first (let v = g.get_clone();) and capture v. RwLockReadGuard and RwLockWriteGuard have the same get and get_clone. At run time new, set and update store a copy of the collections the value brings in (2.13.9); new_unshared skips the copy, the caller guaranteeing that nothing else reaches value's collections (a value just made).

nabi
static STATE: Mutex<List<i32>> = Mutex::new([]);

task::spawn(async {
    using g = STATE.lock() {
        g.update(|xs| { xs.push(42); xs });
    }   // ← g.drop() → lock released ([2.13 marker](213-marker.md))
});

#Avoiding deadlock - try_lock

To avoid deadlock, a non-blocking attempt can be made with try_lock instead of blocking.

nabi
match STATE.try_lock() {
    v: sync::MutexGuard<List<i32>> => using g = v { g.update(|xs| { xs.push(1); xs }); },
    none => { log("locked, skip"); },
}

#Poisoning - none

Nabi's Mutex differs from Rust's PoisonError model. Even if a panic occurs, the lock is released automatically and the next task can enter normally. There are two reasons for this design.

  1. A panic cannot be caught and ends the process, so no other task ever observes the lock state mid-panic. The one exception is #[on_panic] on a function C calls: there the skipped frames do not run their drops, and a Mutex they locked stays locked (return an error value instead of panicking while holding a lock). When an error propagates via throw out of a using block, using calls Drop, so the MutexGuard's drop is responsible for releasing the lock.
  2. Poisoning looks conservative but burdens users heavily and is a false positive in most cases.

Where consistency really must be restored before leaving with an error, handle it explicitly:

nabi
using g = MUTEX.lock() {
    try unsafe_op(g) catch e {
        g.set(known_good_state());
        throw e;
    };
}

#2.16.4. RwLock<T> - read-write split

Where reads vastly outnumber writes, RwLock<T> fits better. Separating multiple readers from a single writer raises throughput.

It suits read-dominated state such as config or caches, and for workloads with rare writes its throughput exceeds that of Mutex.

nabi
static CONFIG: RwLock<Config> = RwLock::new(Config::default());

using c = CONFIG.read() {        // concurrent with other readers OK
    process(c);
}   // ← read guard drop, lock released

using w = CONFIG.write() {       // briefly blocks all readers
    w.set(Config::load_from_file());
}

RwLock<T> is Sync only when T is Send + Sync (2.16.5), so Config here must be Sync. A collection inside one is frozen (RwLock<FrozenDict<K, V>>): readers share it, and a writer replaces it whole (2.16.4b).

As for Mutex, RwLock::new(value) takes value over: using the caller's handle afterwards is a compile error, and so is using what a guard's get returned or set gave after its using block ends, handing over what get returned while the guard holds it (until set gives the lock a new value), or returning it from inside the block (2.13.9). Work on it inside the using block, or keep a clone(). As for Mutex, new and the write guard's set and update store a copy.

The same rule holds for RwLock guards: binding the guard of read / write with a plain let (or if let) that using never releases, or discarding it, is a compile error.

#2.16.4a. Once / Condvar

Two primitives shaped as in Rust. There is no poisoning.

nabi
struct Once { /* ... */ }
impl Once {
    const fn new() -> Once;
    fn call_once(self, f: fn());          // runs f only the first time; concurrent callers wait until it finishes
    fn is_completed(self) -> bool;        // true once a call_once has finished
}

struct Condvar { /* ... */ }
impl Condvar {
    const fn new() -> Condvar;
    fn wait<T>(self, guard: MutexGuard<T>) -> MutexGuard<T>;   // releases the lock and waits, relocks on wakeup
    fn wait_async<T>(self, guard: MutexGuard<T>) -> CondvarWait<T>;   // g = await cv.wait_async(g): suspends only the task
    fn notify_one(self);
    fn notify_all(self);
}

wait can wake spuriously, so the condition is re-checked in a loop. notify_one wakes at least one waiter, and may wake more than one async waiter.

#Async locks and cancellation

The futures of lock_async / read_async / write_async / wait_async do not take the lock on a cancelled poll (2.18.4). A cancelled wait_async ends as follows.

  • If the mutex is free, it re-acquires it, so the caller's using guard releases it as usual.
  • If another task holds it, it leaves without acquiring, and the discarded guard does not release that mutex.

#2.16.4b. Frozen<T> - read-only sharing

A value made once and only read after (configuration, trust anchors, tables) is shared through Frozen<T>. Any thread may read it without a lock.

nabi
struct Frozen<T> { /* ... */ }   // Sync when T: Send

impl<T> Frozen<T> {
    const fn new(value: T) -> Frozen<T>;   // keeps a copy no one else reaches
    fn get(self) -> T;                       // the reader's own copy
}

For one big collection, freeze it instead (2.9.7b): a FrozenList / FrozenDict / FrozenSet is read in place by every thread, with no copy at all. Frozen<T> is for a value made of several parts, some of which are collections that each reader may change in its own copy.

new keeps a copy of the collections value reaches, as a hand-off does (2.13.9), so nothing outside reaches what it holds. get gives each reader a copy of its own: changing it changes nothing the other readers see. Sync parts (a Mutex, a cache that locks itself, a value of an immutable Sync type) are not copied and stay shared, so a get costs a copy of the value's other collections only. Keep big read-only parts out of that copy: hold them as a Sync type, or in a Frozen field of their own that is read where needed.

nabi
struct Settings {
    name: str;
    limits: List<i64>;               // copied by each get: small
    table: Frozen<List<Entry>>;      // shared: read with table.get() where needed
}

static SETTINGS: Frozen<Settings> = Frozen::new(load());

The standard library's TLS Certificate is such a type: never changed once parsed (its accessors give copies), so a Frozen<ClientConfig>'s get shares its trust anchors.

#Read-mostly state: snapshots

State that many threads read and that changes now and then (a server's routing table, a cache, settings that reload) is a frozen snapshot behind a lock. A reader takes the current snapshot (a Sync value may leave the lock's closure or using block) and reads it with no lock held; a writer builds the next snapshot from a copy and puts it in. Readers that took the old one keep reading it, and the collector frees it once none does.

nabi
static ROUTES: Mutex<FrozenDict<str, Route>> = Mutex::new(FrozenDict::new());

fn lookup(path: str) -> Route | none {
    let routes = ROUTES.with(|r| r);          // the current snapshot; the lock is held only for this
    routes.get(path)
}

fn add_route(path: str, r: Route) {
    using g = ROUTES.lock() {
        let next = g.get().to_dict();       // a copy to change
        next[path] = r;
        g.set(next.freeze());
    }
}

RwLock<FrozenDict<..>> works the same way with read_with / write; Mutex is enough when taking the snapshot is all the lock guards.

#2.16.5. Cell<T> - single-threaded interior mutability

Finally, Cell<T> provides interior mutability that works only within a single task.

nabi
struct Cell<T> { /* ... */ }

impl<T> Cell<T> {
    const fn new(value: T) -> Cell<T>;
    fn get(self) -> T            where T: Copy;
    fn set(ref self, value: T);
    #[discardable]
    fn replace(ref self, value: T) -> T;
    #[discardable]
    fn take(ref self) -> T       where T: Default;
}

Cell<T> means thread-local interior mutability, so it is not safe across threads. It can be shared only within a single task, and having no lock makes it very fast.

nabi
let c: Cell<i32> = Cell::new(0);
c.set(42);
let v = c.get();          //→ 42

// sharing across tasks: compile error (Cell has no Send / Sync)
task::spawn(async { c.set(100) });       // ERROR: Cell is not cross-task safe

#Send / Sync markers

Send / Sync are the automatic marker traits of 2.13.9. The types in this chapter follow this policy:

  • Atomic<T>: Send + Sync, Atomic<Ptr<T>> included (the cell holds an address)
  • Mutex<T>: Send + Sync when T: Send
  • RwLock<T>: Send when T: Send; Sync when T: Send + Sync. Its readers share the value at once, so an RwLock of a collection (!Sync) cannot be shared between threads; use Mutex<T>.
  • MutexGuard<T>, RwLockReadGuard<T>, RwLockWriteGuard<T>: Send, !Sync. A guard is good only inside its using block, and the view its get returns is neither Send nor Sync (E0106 tracks it, 2.16.3)
  • Frozen<T>: Sync when T: Send (2.16.4b)
  • FrozenList<T>, FrozenSet<T, S>: Sync when the elements (and the hasher) are Send + Sync; FrozenDict<K, V, S> when K, V and S are (2.9.7b)
  • Cell<T>: neither (single-task only). The task::spawn above is an error because the async block captures the Cell and is therefore not Send

#2.16.6. Module mapping

Every item is defined in core::sync, its one path (0.1.6); there are no per-type submodules.

TypeModuleInternal structure
Atomic<T>core::syncatomic instructions (nabi.atomic.*)
Mutex<T>core::syncfutex / wait queue (per target)
RwLock<T>core::syncfutex + reader counter
Cell<T>core::syncplain wrapper, no lock
MutexGuardcore::syncRAII via Drop
RwLockReadGuard, RwLockWriteGuardcore::syncRAII via Drop
LockFuture, ReadFuture, WriteFuturecore::syncfutures of lock_async / read_async / write_async
Oncecore::syncstate word + wait queue
Condvar, CondvarWaitcore::syncwait queue; CondvarWait is the future of wait_async
Frozen<T>core::synca copy no one else reaches
LoadOrdering, StoreOrdering, UpdateOrderingcore::syncmemory orderings (2.16.2)
AtomicPrimitivecore::syncsealed marker trait

Found a mistake? Edit this page on GitHub. Last updated