Rust Reference ยท Concepts
Concurrency models in Rust
Reference for Rust concurrency: OS threads, scoped threads, message passing with channels, shared state with Arc and Mutex, atomics, Send and Sync, and when to choose async.
Rust offers several ways to run work at the same time, and the type system makes data races a compile-time error. The marker traits Send (a value can move to another thread) and Sync (a shared reference can be used from several threads) are what the compiler checks when you call thread::spawn. If your code compiles, it has no data races; deadlocks and logic races remain possible.
The main models are: OS threads (std::thread), message passing (std::sync::mpsc), shared state (Arc<Mutex<T>>, RwLock, atomics) and async tasks on an executor from a crate such as Tokio.
use std::thread; let handle = thread::spawn(|| 1 + 2); println!("{}", handle.join().unwrap());
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Choosing a model
| Need | Tool |
|---|---|
| A few CPU-bound jobs | thread::spawn, thread::scope |
| Pipeline or worker pool | mpsc channels (one consumer) |
| A shared counter or flag | atomics (AtomicUsize, AtomicBool) |
| Shared structure with writes | Arc<Mutex<T>> |
| Many readers, few writers | Arc<RwLock<T>> |
| Wait until a condition holds | Condvar with a Mutex |
| Thousands of I/O-bound tasks | async with an executor |
| Data-parallel loops | a crate such as rayon (not available on our runner) |
How Send and Sync work
T: Sendmeans ownership of aTcan move to another thread.Rc<T>and raw pointers are notSend.T: Syncmeans&Tcan be shared across threads, which is the same as&T: Send.Cell,RefCellandRcare notSync.- Both are auto traits: a struct is
Sendif all its fields are. Implementing them by hand needsunsafe impl. Mutex<T>isSyncwhenT: Send;Arc<T>isSendwhenT: Send + Sync.
Usage notes
- A panic in a thread is caught at the thread boundary:
join()returnsErr. A panic while holding aMutexpoisons it, and laterlock()calls returnErr. - Lock guards unlock when dropped. Keep critical sections short and never hold a guard across a blocking call or
.await. - Deadlocks happen when threads take locks in different orders; take them in one global order or avoid nested locking.
- Prefer message passing for ownership transfer and shared state for genuinely shared data.
mpsc::sync_channel(n)adds back-pressure. - Thread output order is not deterministic; sort or join results before printing, as the examples do.
- Thread-local data:
thread_local!gives each thread its own copy. - Async is not parallelism by itself. It multiplexes many tasks over few threads; blocking inside an async task stalls the others.