Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ CONCURRENCY WITH A CONTRACT
BUILD NOTE 44 / 53

Understand the cross-thread boundary.

Read the type-level rules behind safe concurrency.

BY NAVAN SAMI◷ 9 MIN READADVANCEDRUST 2024

01 Understand the contract

Send means ownership of a value can be transferred between threads. Sync means shared references to a value can be sent between threads. These auto traits are derived from a type’s fields unless constrained otherwise. Rc is neither Send nor Sync because its reference count is non-atomic. Atomics support synchronized operations on individual primitive values; choosing a memory ordering is a correctness decision. Relaxed is suitable for an independent counter whose value does not publish other data, especially when joins provide the final completion synchronization.

02 Make it concrete

This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.

lessons/send-sync/src/main.rs
use std::sync::{
    Arc,
    atomic::{AtomicUsize, Ordering},
};
use std::thread;
fn main() {
    let count = Arc::new(AtomicUsize::new(0));
    let workers: Vec<_> = (0..3)
        .map(|_| {
            let c = Arc::clone(&count);
            thread::spawn(move || {
                c.fetch_add(1, Ordering::Relaxed);
            })
        })
        .collect();
    for worker in workers {
        worker.join().unwrap();
    }
    println!("{}", count.load(Ordering::Relaxed));
}
↳ EXPECTED OUTPUT
3
  1. 1

    Atomic fetch_add avoids a lost increment.

  2. 2

    This counter does not publish any separate payload.

  3. 3

    join ensures each worker has finished before the final load.

From the extracted rust-workbench folder
cargo run -p lesson_send_sync

03 Mind the boundary

04 Your next build

A SMALL MISSION

Use compile-time generic assertions to check that String is Send and Sync.

Reveal one possible solution +
solutions/send-sync/src/main.rs
fn assert_send<T: Send>() {}
fn assert_sync<T: Sync>() {}
fn main() {
    assert_send::<String>();
    assert_sync::<String>();
    assert_send::<std::sync::Arc<String>>();
}

05 Check your reasoning

QUICK SIGNAL CHECK

What does Sync mean?

ONE MORE CONTRACT YOU CAN EXPLAIN.

Understand it.
Then make it yours.

Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.