Skip to content
Tutorials Center
My learning

Topics

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.

Rust
use std::thread;
let handle = thread::spawn(|| 1 + 2);
println!("{}", handle.join().unwrap());

Try it

Rust Threads, join handles and scoped threads

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.

Rust Channels and shared state

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.

Rust Rc is not Send

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: Send means ownership of a T can move to another thread. Rc<T> and raw pointers are not Send.
  • T: Sync means &T can be shared across threads, which is the same as &T: Send. Cell, RefCell and Rc are not Sync.
  • Both are auto traits: a struct is Send if all its fields are. Implementing them by hand needs unsafe impl.
  • Mutex<T> is Sync when T: Send; Arc<T> is Send when T: Send + Sync.

Usage notes

  • A panic in a thread is caught at the thread boundary: join() returns Err. A panic while holding a Mutex poisons it, and later lock() calls return Err.
  • 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.