Shared-State Concurrency
Recipe | Crates | Categories |
---|---|---|
Maintain a Global Mutable State | ||
Mutexes | ||
parking_lot |
Channels are similar to single ownership, because once you transfer a value down a channel, you should no longer use that value. Shared memory concurrency is like multiple ownership: multiple threads can access the same memory location at the same time.
The Rust standard library provides smart pointer types, such as Mutex<T>
and Arc<T>
, that are safe to use in concurrent contexts.
Maintain a Global Mutable State
Declare global state using lazy static
. lazy static
⮳ creates a globally available static ref
which requires a std::sync::Mutex
⮳ to allow mutation (also see std::sync::RwLock
⮳). The std::sync::Mutex
⮳ wrap ensures the state cannot be simultaneously accessed by multiple threads, preventing race conditions. A std::sync::MutexGuard
⮳ must be acquired to read or mutate the value stored in a std::sync::Mutex
⮳.
Mutexes
Allow access to data from one thread at a time.
parking_lot
parking_lot
⮳ is a more compact and efficient implementation of the standard synchronization primitives.
parking_lot
⮳ provides implementations of parking_lot::Mutex
⮳, parking_lot::RwLock
⮳, parking_lot::Condvar
⮳ and parking_lot::Once
⮳ that are smaller, faster and more flexible than those in the Rust standard library. It also provides a parking_lot::ReentrantMutex
⮳ type.
std::sync::Mutex
⮳ works fine, but parking_lot
⮳ is faster.
Related Topics
- Lazy Initialization.
- Memory Management.