Understand the cross-thread boundary.
Read the type-level rules behind safe concurrency.
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.
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));
}3
- 1
Atomic fetch_add avoids a lost increment.
- 2
This counter does not publish any separate payload.
- 3
join ensures each worker has finished before the final load.
cargo run -p lesson_send_sync03 Mind the boundary
04 Your next build
Use compile-time generic assertions to check that String is Send and Sync.
Reveal one possible solution +
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
What does Sync mean?
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.