Step Into Rust · Lesson 12 · Sharing & Concurrency
Threads, Channels and Shared State
Spawning and joining threads, Arc and Mutex, message passing with channels, and scoped threads that borrow. Fearless concurrency in practice.
- ~40 minreading and coding
- 4missions
- membersaccess
- Rustlanguage
Part of Step Into Rust. The full lesson, its missions and the real compiler and debugger are in the course. Try a free lesson first to see how it works.
std::thread::spawn runs a closure on a new operating-system thread and returns a JoinHandle. join() waits for the thread and hands back the closure's return value:
In this lesson
- Spawning a thread
- Rust stops data races at compile time
- Shared, mutable state: Arc<Mutex<T>>
- Message passing: channels
- Scoped threads: borrow instead of Arc
Missions
- Split the work
- Lose no updates
- Messages instead of sharing
- Borrow across threads