Rust Tutorial: Concurrency
Spawn threads, share data with Arc and Mutex, and pass messages with channels.
Fearless concurrency
Rust's type system prevents data races at compile time. The same ownership rules that manage memory also manage thread safety.
What you'll learn in this Rust concurrency tutorial
This interactive Rust tutorial has 8 hands-on exercises. Estimated time: 22 minutes.
- Spawn a thread — `thread::spawn` runs a closure in a new OS thread.
- move closure in thread — Threads need `move` closures to take ownership of captured data.
- Arc<T> — shared across threads — `Arc<T>` (Atomic Reference Count) is `Rc<T>` for multiple threads — thread-safe.
- Mutex<T> — exclusive access — `Mutex<T>` ensures only one thread accesses the data at a time.
- Channels — message passing — `std::sync::mpsc` provides a multi-producer, single-consumer channel.
- Multiple producers — Clone the transmitter for multiple senders.
- Rayon-style data parallelism — Use `std::thread::scope` (Rust 1.63+) for scoped threads that can borrow the parent's data.
- Send and Sync — `Send` means a type can be sent to another thread. `Sync` means it can be shared.
Rust Concurrency concepts covered
- Fearless concurrency