Concurrency
This section covers concurrent programming, and specifically parallel programming.
Parallelism implies:
- True simultaneous execution of multiple tasks on multiple cores or processors.
- Mechanism: uses operating system threads.
- Important for CPU-heavy computations.
- Often requires explicit management of threads and thread pools.
- Requires careful synchronization to prevent data races (using mechanisms like mutexes or atomics).
- Overhead due to thread creation and switching.
Key constructs in Rust:
- Threads are independent units of execution that can be spawned using e.g.
std::thread::spawn
⮳. - Mutexes e.g.
std::sync::Mutex
⮳ protect shared data from race conditions. - Channels e.g.
std::sync::mpsc
⮳ allow threads to communicate and exchange data.
Explicit Threads
Creating and managing threads, using mutexes and other synchronization primitives.
Recipe | Crates | Categories |
---|---|---|
Use spawn, join | [ | |
Use scoped threads |
Threadpools
Using thread pools for efficient task execution.
Recipe | Crates | Categories |
---|---|---|
Calculate the SHA256 of ISO Files Concurrently | ||
Draw a Fractal, Dispatching Work to a Thread Pool |
Multithreading with the crossbeam
Crate
Recipe | Crates | Categories |
---|---|---|
Spawn a Short-lived Thread | ||
Create a Parallel Pipeline | ||
Pass Data Between Two Threads |
Message Passing and Channels
Communicating between threads using channels.
Recipe | Crates | Categories |
---|---|---|
Multiple Producers, Single Consumer | ||
crossbeam-channel | ||
flume |
Shared State
Shared Memory. Using atomic types for thread-safe data access.
Recipe | Crates | Categories |
---|---|---|
Maintain a Global Mutable State | ||
Mutexes | ||
parking_lot |
Concurrent Data Structures
Recipe | Crates | Categories |
---|---|---|
Bounded Multi-producer Multi-consumer Queue | ||
dashmap | ||
flurry | ||
papaya |
Data Parallelism
Using iterators in parallel with crates like rayon
⮳.
Send
and Sync
Recipe | Crates | Categories |
---|---|---|
Existing Implementations of Send and Sync | ||
Implementing Send and Sync | ||
Send and Sync Traits |
Related Topics
- Async.
- Async and Blocking.
- Async Channels.
- Concurrent Data Structures.
- Message Passing.
- Explicit Threads.
- Processor.
References
⮳.
- Rust Atomics⮳.