Module 9 · Lesson 42 of 112

Condvar, Barrier, and atomics

Coordinate Rust threads with condition variables, barriers, and one-time initialization, and use atomic operations for shared flags, integers, and pointers.

  • Beginner to advanced
  • 10 min read
  • 19 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM with stable Rust and Cargo installed. The examples use ordinary threads and need no board.

Your place in the module
By the end you can 4 objectives
  • Write a condition-variable wait loop that checks mutex-protected state before proceeding.
  • Set a barrier's participant count and identify where each thread must wait.
  • Choose between OnceLock for a shared value and Once for a one-time action.
  • Predict the results of atomic loads, stores, swaps, and successful or failed compare-and-exchange operations.
Video coming soonCondvar, Barrier, and atomics
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Channels, Mutex, and RwLock
  • The receiver drains queued messages before reporting disconnection after the last sender drops.
  • A MutexGuard gives access to the protected value and releases the mutex when it drops.
  • An RwLock admits multiple readers or one exclusive writer.
01

Wait for a change with Condvar

4 min read

The last lesson shared state with channels and locks. This lesson answers the remaining synchronization primitives: Condvar, Barrier, and atomics.

An embedded Linux sensor service may have a producer reading samples and a worker processing them. When the worker finds an empty queue, it needs to wait while giving the producer access to that same queue. There is also a timing problem. If the worker unlocks the queue first and then starts waiting in a separate step, the producer can insert a sample and issue its notification between those steps. The worker could then sleep with a sample already available. POSIX documents the unlock-and-wait behavior that addresses this problem. Rust's Condvar::wait provides the corresponding behavior through a mutex guard. pthread_cond_wait(3p)

A gives the worker a specific test to perform. For the sensor queue, the predicate could be “the queue contains a sample or shutdown has been requested.” For a small example, a single Boolean inside a Mutex is enough. The thread that makes the predicate true changes the Boolean under the mutex, and the thread that waits reads it under the same mutex.

rust
use std::sync::{Arc, Condvar, Mutex};
use std::thread;

fn main() {
    let state = Arc::new((Mutex::new(false), Condvar::new()));
    let worker_state = Arc::clone(&state);

    let worker = thread::spawn(move || {
        let (ready, changed) = &*worker_state;
        let mut ready = ready.lock().unwrap();

        while !*ready {
            ready = changed.wait(ready).unwrap();
        }
        assert!(*ready);
    });

    let (ready, changed) = &*state;
    *ready.lock().unwrap() = true;
    changed.notify_one();
    worker.join().unwrap();
}

wait takes ownership of the guard. As it enters the wait, it releases the mutex atomically with respect to the condition-variable wait protocol. Before returning, it reacquires the mutex and gives the caller a guard again. The producer can therefore acquire the mutex while the worker is asleep. The waiter's read after waking is protected by the reacquired lock. The example uses unwrap() to stop on a poisoned lock or a failed worker join.

If the main thread writes true before the worker takes the lock, the worker sees true on its first check and skips wait. If the worker checks first and finds false, the main thread can take the lock after wait releases it, write true, and notify the waiter. Both schedules work because true remains in the shared state. A Condvar notification sent when nobody is waiting is discarded. The mutex-protected state is what allows a late worker to proceed.

Condition-variable wait loopCheck under lockWaiting without lockProceed under lockTransitionsFalse: release and waitCheck under lockWaiting without lockWake and reacquireWaiting without lockCheck under lockPredicate is trueCheck under lockProceed under lockCheck under lockWaiting without lockProceed under lockTransitionsFalse: release and waitCheck underlockWaitingwithoutlockWake and reacquireWaitingwithoutlockCheck underlockPredicate is trueCheck underlockProceedunder lock
The worker checks the predicate while holding the mutex, including after every wakeup.

Keep the test in a while loop. A wait can return spuriously, and in a queue with several consumers another worker can take the available item before the woken thread reacquires the lock. Either way, a woken worker can observe an empty queue. The loop sends it back to sleep if the predicate is still false. For a queue, inspect and remove the item in the same locked section so that another worker cannot take it between the test and the removal.

Use notify_one() when one waiting worker can make progress, such as when a producer adds one sample to a queue whose consumers all wait for the same condition. The call wakes one blocked waiter if there is one, and the choice of waiter is unspecified. Use notify_all() when a change allows every waiter to proceed. For example, set shutdown = true under the queue mutex, then call notify_all() so all sleeping workers can wake, reacquire the mutex in turn, and examine the shutdown flag. Rust allows the notification while holding the lock or after releasing it. In the example the assignment ends before notification, allowing the woken worker to acquire the mutex as soon as it can run. pthread_cond_broadcast(3p)

02

Coordinate arrivals and one-time initialization

3 min read

Suppose two workers have startup tasks and the main thread must wait until both workers have reached the end of startup. With Barrier::new(3), the two workers and main each call wait() on the same barrier. The first arrivals block. Once all three have arrived, all three calls can return. This is an N-thread rendezvous, where N is the number of participants in the round. The participants can resume in any order after the rendezvous. The POSIX barrier interface describes the same arrival-count pattern. pthread_barrier_wait(3p)

The following program uses a OnceLock to give both workers access to the same configuration value. Each worker reads the value before reaching the barrier, and main checks that it is available after reaching the barrier.

rust
use std::sync::{Arc, Barrier, OnceLock};
use std::thread;

static CONFIG: OnceLock<usize> = OnceLock::new();

fn main() {
    let startup = Arc::new(Barrier::new(3));
    let mut workers = Vec::new();

    for _ in 0..2 {
        let startup = Arc::clone(&startup);
        workers.push(thread::spawn(move || {
            let batch_size = CONFIG.get_or_init(|| 16);
            assert_eq!(*batch_size, 16);
            startup.wait();
        }));
    }

    startup.wait();
    assert_eq!(CONFIG.get(), Some(&16));

    for worker in workers {
        worker.join().unwrap();
    }
}
A barrier with three participantsWorker AReadconfigurationCall waitCan resumeWorker BReadconfigurationCall waitCan resumeMainSpawn workersCall waitCan resumeThe rows show each thread's order. Arrival order can vary.
Both workers and main must call wait before any participant can continue past the barrier.

The count comes from the calls to wait(), so include main in the count whenever main also waits. A barrier has no way to account for a worker that exits early or panics before its call. In that case the other arrivals can remain blocked. A Rust Barrier is reusable. The same group can call wait() again at the end of a second stage, as long as every participant reaches the second call. For each round, exactly one returned BarrierWaitResult reports is_leader() as true. A thread can use that result to perform a single action for the round. If all participants need that action to finish before they continue, they can all wait at a second rendezvous after the leader performs it.

OnceLock<T> coordinates initialization of a value of type T. get_or_init returns a shared reference &T. When concurrent callers supply initializers for an empty cell, only one initializer runs if it completes successfully. A caller that arrives during successful initialization waits for the value. Later callers reuse the stored value, and their initializer closures are skipped. get() is useful when a caller wants to check availability immediately. It returns None if the value is absent or still being initialized. If an initializer panics, the cell stays empty and a subsequent call can initialize it.

Use std::sync::Once when the shared outcome is completion of an action. For example, in a service whose setup needs to register a process-wide diagnostics callback, a shared Once can protect the registration call. Declare static REGISTER: Once = Once::new() after importing Once, then have each caller invoke REGISTER.call_once with a closure that performs the registration. A successful call returns after the action has completed, whether this caller ran it or waited for another thread. If the action panics, that Once is poisoned and later calls to call_once panic too. When callers need a typed configuration or lookup table, OnceLock provides the initialized value directly.

In the example, get_or_init can return while the other worker has yet to start. The barrier covers a different condition. By the time main's wait() returns, both workers have reached their own wait() calls after reading the configuration. The joins then wait for the worker threads to finish.

03

Read and update a single value atomically

4 min read

An atomic type lets threads perform indivisible operations on a shared value through a shared reference. A Linux service might use AtomicBool for a stop request that workers check between operations, AtomicUsize for a shared machine-word unsigned integer, or AtomicPtr<T> for a shared raw pointer of type *mut T. Each atomic object represents one value. Updating a flag and an integer with two separate atomic calls leaves an interval in which another thread can observe the first update before the second. Use a mutex when several fields must be observed or changed as one consistent state.

load(order) reads the current value. store(value, order) replaces it and returns (). swap(value, order) installs the new value and returns the previous value as one indivisible operation. For a stop flag, a coordinator can call stop.store(true, Ordering::SeqCst) and workers can call stop.load(Ordering::SeqCst) at points where they can safely stop. If several callers request shutdown, stop.swap(true, Ordering::SeqCst) also tells each caller whether the flag was already set at the instant of its update. That works as a first-request test when the flag starts at false and is never reset. A sleeping worker on a condition variable still needs a notification through that condition variable's protocol.

Use compare_exchange when the update depends on what value is present at the instant of the update. It takes an expected value, a replacement value, a success ordering, and a failure ordering. Compare-and-exchange, often called CAS, compares and conditionally replaces in a single operation. On success it returns Ok(previous), where previous equals the expected value. On failure it returns Err(observed) with the value it read during the comparison and leaves the atomic unchanged. Another operation may change the value again after the comparison.

rust
use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};

fn main() {
    let slot = AtomicUsize::new(0);
    assert_eq!(slot.load(SeqCst), 0);

    slot.store(1, SeqCst);
    assert_eq!(slot.swap(2, SeqCst), 1);

    assert_eq!(slot.compare_exchange(2, 3, SeqCst, SeqCst), Ok(2));
    assert_eq!(slot.compare_exchange(2, 4, SeqCst, SeqCst), Err(3));
    assert_eq!(slot.load(SeqCst), 3);
}

This program uses one thread so the returned values are predictable. In a threaded program, suppose zero means a diagnostic capture slot is free and one means it has been claimed. Two threads can both load zero before either stores one, so a load followed by a store would let both believe they claimed the slot. With compare_exchange(0, 1, SeqCst, SeqCst), the first successful caller changes the value to one in the same operation that checks for zero. A competing caller fails while the slot is still claimed. swap can report the previous value, but it writes its replacement even if the previous value differs from the value the caller expected.

Atomic writes and return valuesWriteReturnLoadNoneObservedvalueStoreNew valueUnitSwapNew valuePreviousvalueCAS successReplacementvalueOk(previous)CAS failureNoneErr(observed)
Compare what each atomic operation writes and returns.

AtomicPtr<T> supports the same operations on pointer values. For example, AtomicPtr::<u8>::new(std::ptr::null_mut()) creates an atomic pointer initially containing null. Swapping in a valid raw pointer returns the previous pointer, which is null on the first swap if there were no intervening writes. The atomic operation covers the pointer value. The memory it points to has separate lifetime and access requirements. A reader can load a pointer before another thread replaces it, then still hold the old pointer after the replacement. Dereferencing a raw pointer requires unsafe and proof that the pointed-to object is still valid for the access. If readers need shared ownership of replaceable data, a mutex around an Arc<T> lets each reader clone the Arc while holding the lock and keep the old allocation alive after releasing it.

std::sync::atomic::Ordering is the enum that describes the memory-ordering guarantees an operation requests. Its variants are Relaxed, Release, Acquire, AcqRel, and SeqCst. The examples use SeqCst throughout. Every operation shown accepts it, and sequentially consistent operations share a single total order. CAS has two ordering arguments because success reads and writes the value, while failure only reads it. The failure argument can be Relaxed, Acquire, or SeqCst. The weaker orderings and the precise guarantees they give for accesses to other memory belong to the next lesson.

When reviewing a thread interaction, identify what the receiving thread must observe before it can continue. A mutex-protected predicate can describe several fields and lets a worker sleep while they are unsuitable. A barrier represents arrivals at a stage boundary, and OnceLock represents availability of an initialized value. An atomic flag or integer gives a thread a way to inspect or change a single value at an explicit point in its work. “Memory ordering and lock-free counters” follows by asking what these atomic operations guarantee about other memory and how threads can update a shared counter without a mutex.

Key takeaways

  • A condition-variable waiter rechecks a shared predicate after reacquiring the mutex.
  • A barrier releases a round when the configured number of calls to wait have arrived.
  • OnceLock provides a shared initialized value, while Once coordinates completion of an action.
  • An atomic operation acts on one value, and compare_exchange replaces that value only if it equals the expected value.
Reflect
  1. Explain to a colleague, in two sentences: write a condition-variable wait loop that checks mutex-protected state before proceeding.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close