Chapter 22: Fearless Concurrency
Modern computing often relies on running multiple units of work concurrently to improve responsiveness and performance. In Rust, these units of work are typically referred to as tasks or threads, depending on the abstraction level. Thanks to Rust's ownership model and type system, concurrency can be managed robustly, preventing data races and undefined behavior at compile time while drastically reducing runtime errors.
In this chapter, we introduce fundamental concurrency concepts and demonstrate how to create and manage threads in Rust. We then explore:
- Safe data sharing with mutexes, read-write locks, and condition variables
- Inter-thread communication with channels
- The Rayon library for high-level data parallelism
- Atomic types for low-level lock-free concurrency
- Scoped threads (introduced in Rust 1.63)
- Leveraging SIMD (Single Instruction, Multiple Data) optimizations
Where relevant, we compare Rust's approach to concurrency with techniques in C and C++ to highlight the advantages Rust offers for safe and efficient parallel programming.