← Runtimes
Runtimes

Rust Send, Sync, and thread boundaries

Know which values may cross threads, and what the compiler cannot check.

Rust checks whether data may cross thread boundaries; the design still determines how long work holds a lock.

Outcome

Explain what Send and Sync guarantee, choose thread-safe types for moving and sharing data, and hold locks only as long as the update needs.

Terminology (5)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Send
A type is Send if ownership of a value can safely move to another thread. Rc<T> is not Send; Arc<T> is Send when T is both Send and Sync.
Sync
A type is Sync when &T is Send: a shared reference can safely cross threads. RefCell<T> is not Sync; Mutex<T> is Sync when T is Send.
Arc
An atomically reference-counted shared owner. Arc<T> is Send and Sync when T is both Send and Sync; it does not make an unsynchronized inner value thread-safe.
Mutex<T>
Owns its data; lock() returns a MutexGuard that gives access and releases the lock when dropped.
MutexGuard
The handle returned by lock(); the lock is held for exactly as long as the guard is alive.

Moving and sharing across threads

Send describes whether ownership of a value may safely move to another thread. Sync describes whether a shared reference may safely cross that boundary: T is Sync when &T is Send. These are type guarantees checked when constructing threaded code, rather than measurements of how the threads happened to run.

Shared ownership and synchronized access solve different problems. Keeping a value alive for several threads does not by itself coordinate mutation. A mutex grants access through a guard whose lifetime determines the critical section. The compiler’s safety checks leave the program responsible for useful overlap, completion and the scope of that guard.

01Send and Sync

The compiler checks what crosses a thread boundary

The image exporter is ready to process tiles on four worker threads. All four need the same output settings, and the batch report must include every completed tile. Rust rejects the shared settings, then the shared totals. After those errors are fixed, a lock still makes the converter waits happen one at a time.

thread::spawn requires a Send + 'static closure and a Send + 'static return value. Captured values must satisfy the closure’s bounds; owned data can satisfy 'static without being leaked forever. Arc<T> can cross threads when T is both Send and Sync. These auto traits usually follow a type’s fields, with standard types defining their own bounds. Rc<T> uses a non-atomic count and is neither Send nor Sync. RefCell<T> can move when T is Send, but its unsynchronized borrow tracking prevents Sync.

Common types at a thread boundary
TypeSendSyncCandidate for this use
Rc<T>NoNoArc<T> if T: Send + Sync
RefCell<T>If T isNoMutex<T>, RwLock<T>
Cell<u64>YesNoAtomicU64
Arc<Mutex<T>>If T is SendIf T is Send(already thread-safe)
A program wraps its config in Rc and moves a clone into each spawned thread. What happens?

02What the compiler leaves to you

A guard holds the lock until it is dropped

The exporter now compiles, but its shared accounting guard covers the converter wait as well as the update. Safe immutable sharing needs no mutex; safe shared mutation needs suitable synchronization. Neither Send nor Sync chooses the length of a critical section. This reduced probe replaces each conversion with a 50 ms sleep and each report update with adding 1, so we can examine the guard’s lifetime separately from image processing.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};

/// Run four threads that each do 50 ms of work and then add 1 to a shared total.
fn run(hold_during_work: bool) -> (u32, u128) {
    let total = Arc::new(Mutex::new(0));
    let start = Instant::now();

    let handles: Vec<_> = (0..4)
        .map(|_| {
            let total = Arc::clone(&total);
            thread::spawn(move || {
                if hold_during_work {
                    let mut guard = total.lock().unwrap();
                    thread::sleep(Duration::from_millis(50));
                    *guard += 1;
                } else {
                    thread::sleep(Duration::from_millis(50));
                    *total.lock().unwrap() += 1;
                }
            })
        })
        .collect();
    for handle in handles {
        handle.join().unwrap();
    }

    let elapsed = (start.elapsed().as_millis() + 25) / 50 * 50;
    let count = *total.lock().unwrap();
    (count, elapsed)
}

fn main() {
    let (total, ms) = run(true);
    println!("guard held during work: total {total}, about {ms} ms");
    let (total, ms) = run(false);
    println!("guard only for the update: total {total}, about {ms} ms");
}
terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
cargo run
In the recorded run, with four 50 ms sleeps and little scheduling overhead, about how long did each version take?

03Practice

Finish the export batch

Easy shares one Config; its independent completion metrics already use supplied AtomicU64 counters. Their report loads both only after all worker joins, so it needs no intermediate two-field snapshot. Medium instead has plain fields grouped in one mutable Stats; choosing safe shared access to that state is your task. Hard gives the four workers a common tile queue so each can take the next available item. A successful claim must transfer an item out of the queue once, and an empty queue must let a worker finish. VecDeque::pop_front needs &mut self and returns Option<T>, owning the removed item; front only borrows an item and leaves it queued. The caller supplies the queue and joins the workers. Decide which data each guard protects, and which work can continue after that guard is gone.

The export workers

Share the exporter’s settings and accounting, then drain its work queue without holding a guard across independent conversion waits.

  1. easy · R-SEND-V4-1 Share the config
  2. medium · R-SEND-V4-2 Share the totals
  3. hard · R-SEND-V4-3 Hold locks briefly
Check this idea later
A read-only Cache contains Send + Sync + 'static data. Its handle is Rc<Cache>, and a new thread needs shared ownership. What change compiles?
Arc<RefCell<Vec<Job>>> is passed to worker threads. What does the compiler say?
Workers lock the same map, call a slow HTTP API, then update the map while holding the guard. The call needs no protected map state. What happens to these guarded operations?
Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.