#2.16. sync - Concurrency primitives
On this page
- 2.16.1. Overview of the primitives
- 2.16.2. Atomic<T> - lock-free atomics
- LoadOrdering, StoreOrdering, UpdateOrdering
- Example
- CAS (compare-and-swap)
- 2.16.3. Mutex<T> - exclusive lock
- Example
- Avoiding deadlock - try_lock
- Poisoning - none
- 2.16.4. RwLock<T> - read-write split
- 2.16.4a. Once / Condvar
- Async locks and cancellation
- 2.16.4b. Frozen<T> - read-only sharing
- Read-mostly state: snapshots
- 2.16.5. Cell<T> - single-threaded interior mutability
- Send / Sync markers
- 2.16.6. Module mapping
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.
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.
| Type | Meaning | Where 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 writer | read-heavy state |
Cell<T> | thread-local interior mutability (no lock) | single-threaded mutable |
Once | runs an initializer exactly once (2.16.4a) | lazy global setup |
Condvar | waits 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.
struct Atomic<T> {
// internal: a one-element cell driven by per-T atomic instructions
}
trait AtomicPrimitive { /* marker: i8/i16/i32/i64/isize, u8/u16/u32/u64/usize, bool, Ptr<T> */ }
impl<T: AtomicPrimitive + PartialEq> Atomic<T> {
const fn new(value: T) -> Atomic<T>;
fn load(self, ordering: LoadOrdering = SeqCst) -> T;
fn store(self, value: T, ordering: StoreOrdering = SeqCst);
#[discardable]
fn swap(self, value: T, ordering: UpdateOrdering = SeqCst) -> T;
fn compare_exchange(
self, current: T, new: T,
success: UpdateOrdering, failure: LoadOrdering,
) -> Result<T, T>; // the failure result is a value too, not an error
fn compare_exchange_weak(
self, current: T, new: T,
success: UpdateOrdering, failure: LoadOrdering,
) -> Result<T, T>; // the failure result is a value too, not an error
// integers only; each fetch_* is #[discardable]
fn fetch_add(self, value: T, ordering: UpdateOrdering = SeqCst) -> T;
fn fetch_sub(self, value: T, ordering: UpdateOrdering = SeqCst) -> T;
fn fetch_and(self, value: T, ordering: UpdateOrdering = SeqCst) -> T;
fn fetch_or(self, value: T, ordering: UpdateOrdering = SeqCst) -> T;
fn fetch_xor(self, value: T, ordering: UpdateOrdering = SeqCst) -> T;
}
impl Atomic<i32> {
fn wait(self, expected: i32); // waits while the value is expected
fn wait_timeout(self, expected: i32, timeout: Duration); // wait, at most timeout (none left: returns at once)
fn wake(self); // wakes every thread waiting on this cell
}
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).
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
| Ordering | Meaning |
|---|---|
Relaxed | no synchronization (counters etc.) |
Acquire | synchronization guaranteed after the load |
Release | synchronization guaranteed before the store |
AcqRel | both directions for a read-modify-write |
SeqCst | global 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.
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.
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.
struct Mutex<T> {
// internal: futex + payload
}
impl<T> Mutex<T> {
const fn new(value: T) -> Mutex<T>;
const unsafe fn new_unshared(value: T) -> Mutex<T>; // new without the hand-off copy
fn lock(self) -> MutexGuard<T>; // blocks the thread
fn lock_async(self) -> LockFuture<T>; // await m.lock_async(): suspends only the task (Future<Output = MutexGuard<T>>)
fn try_lock(self) -> MutexGuard<T> | none; // non-blocking
fn with<R>(self, f: fn(T) -> R) -> R; // lock, f(value), unlock
}
struct MutexGuard<T> { /* RAII guard */ }
impl<T> Drop for MutexGuard<T> {
fn drop(ref self) {
// futex_wake + release the lock
}
}
impl<T> MutexGuard<T> {
fn get(self) -> T; // a scoped view of the protected value
fn get_clone(self) -> T where T: Clone; // a deep copy, free to outlive the lock
fn set(self, value: T); // replaces the value
fn update(self, f: fn(T) -> T); // reads, transforms and writes back
}
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).
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.
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.
- 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 aMutexthey locked stays locked (return an error value instead of panicking while holding a lock). When an error propagates viathrowout of ausingblock,usingcalls Drop, so theMutexGuard's drop is responsible for releasing the lock. - 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:
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.
struct RwLock<T> { /* ... */ }
impl<T> RwLock<T> {
const fn new(value: T) -> RwLock<T>;
fn read(self) -> RwLockReadGuard<T>; // multiple readers OK
fn write(self) -> RwLockWriteGuard<T>; // single writer
fn try_read(self) -> RwLockReadGuard<T> | none;
fn try_write(self) -> RwLockWriteGuard<T> | none;
fn read_async(self) -> ReadFuture<T>; // await l.read_async(): suspends only the task
fn write_async(self) -> WriteFuture<T>;
fn read_with<R>(self, f: fn(T) -> R) -> R; // as Mutex::with, under the read lock
fn write_with<R>(self, f: fn(T) -> R) -> R; // as Mutex::with, under the write lock
}
struct RwLockReadGuard<T> { /* RAII guard: releases the read lock */ }
impl<T> RwLockReadGuard<T> {
fn get(self) -> T; // a scoped view of the protected value
fn get_clone(self) -> T where T: Clone; // a deep copy, free to outlive the lock
}
struct RwLockWriteGuard<T> { /* RAII guard: releases the write lock */ }
impl<T> RwLockWriteGuard<T> {
fn get(self) -> T;
fn get_clone(self) -> T where T: Clone;
fn set(self, value: T); // replaces the value
fn update(self, f: fn(T) -> T); // reads, transforms and writes back
}
// both guards: Drop (releases the lock), Debug, !Sync
It suits read-dominated state such as config or caches, and for workloads with rare writes its throughput exceeds that of Mutex.
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.
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
usingguard 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.
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.
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.
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.
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.
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 whenT: SendRwLock<T>: Send whenT: Send; Sync whenT: Send + Sync. Its readers share the value at once, so anRwLockof a collection (!Sync) cannot be shared between threads; useMutex<T>.MutexGuard<T>,RwLockReadGuard<T>,RwLockWriteGuard<T>: Send,!Sync. A guard is good only inside itsusingblock, and the view itsgetreturns is neitherSendnorSync(E0106 tracks it, 2.16.3)Frozen<T>: Sync whenT: Send(2.16.4b)FrozenList<T>,FrozenSet<T, S>: Sync when the elements (and the hasher) areSend + Sync;FrozenDict<K, V, S>whenK,VandSare (2.9.7b)Cell<T>: neither (single-task only). Thetask::spawnabove is an error because theasyncblock captures theCelland is therefore notSend
#2.16.6. Module mapping
Every item is defined in core::sync, its one path (0.1.6); there are no per-type submodules.
| Type | Module | Internal structure |
|---|---|---|
Atomic<T> | core::sync | atomic instructions (nabi.atomic.*) |
Mutex<T> | core::sync | futex / wait queue (per target) |
RwLock<T> | core::sync | futex + reader counter |
Cell<T> | core::sync | plain wrapper, no lock |
MutexGuard | core::sync | RAII via Drop |
RwLockReadGuard, RwLockWriteGuard | core::sync | RAII via Drop |
LockFuture, ReadFuture, WriteFuture | core::sync | futures of lock_async / read_async / write_async |
Once | core::sync | state word + wait queue |
Condvar, CondvarWait | core::sync | wait queue; CondvarWait is the future of wait_async |
Frozen<T> | core::sync | a copy no one else reaches |
LoadOrdering, StoreOrdering, UpdateOrdering | core::sync | memory orderings (2.16.2) |
AtomicPrimitive | core::sync | sealed marker trait |
Found a mistake? Edit this page on GitHub. Last updated