Skip to content

Chapter 7 of 8

Concurrency in Rust

Rust's concurrency story begins with `std::thread::spawn`, which takes a closure and returns a `JoinHandle`. Calling `.join().unwrap()` on the handle blocks the current thread until the spawned thread has finished. Closures sent to threads almost always need the `move` keyword so that they own the data they operate on rather than borrowing it from the spawning thread, which would otherwise cause lifetime problems once the spawning thread moves on.

Two marker traits underpin safe concurrency. `Send` indicates that a value of a type can be transferred to another thread, while `Sync` indicates that a value can be referenced from multiple threads — formally, `&T` is `Send` whenever `T` is `Sync`. Most standard types implement both automatically. The single-threaded reference-counted pointer `Rc` is an exception, because its non-atomic counter is not thread-safe, and it implements neither marker.

For shared state across threads, the standard library offers `Arc`, which provides thread-safe shared ownership through atomic reference counting, paired with `Mutex`, which provides interior mutability behind a lock. The combination `Arc>` is a frequent pattern for letting multiple threads read and write a shared value safely. The mutex serializes access while the `Arc` makes the locked value shared.

When shared state is awkward, channels provide an alternative based on message passing. The `std::sync::mpsc` module — short for multiple producer, single consumer — gives you a sender `tx` and a receiver `rx`. The sender hands values to the receiver, which can collect them. Channels naturally serialize access through communication rather than through shared locks, and they are often the most ergonomic way to coordinate work between threads.

All chapters
  1. 1Foundations of Rust Memory Safety
  2. 2Structures, Enums, and Pattern Matching
  3. 3Error Handling with Option and Result
  4. 4Traits, Generics, and Polymorphism
  5. 5Iterators, Closures, and Functional Patterns
  6. 6Modules, Crates, Cargo, and Testing
  7. 7Concurrency in Rust
  8. 8Smart Pointers and Unsafe Rust

Drill it

Reading is not remembering. These come from the Rust Programming deck:

Q

What is Rust?

Rust is a systems programming language focused on safety, speed, and concurrency. It achieves memory safety without a garbage collector through its ownership sy...

Q

What is ownership in Rust?

Ownership is Rust's core memory management concept. Each value has exactly one owner, and when the owner goes out of scope, the value is dropped (freed). This p...

Q

What are the three ownership rules in Rust?

Each value in Rust has a single ownerThere can only be one owner at a timeWhen the owner goes out of scope, the value is dropped

Q

What is borrowing in Rust?

Borrowing lets you reference a value without taking ownership. You create a reference with &. The original owner retains ownership while the borrower can re...