On this page
Mutex
Prev: sync | Up: sync | Next: `RwLock`
Rel: sync, rust/builtins
Ref: Rust std — Mutex
Tags: #public #prog #rust #stdlib #sync #tier/core
Signature & Overview
Mutex<T>
Mutual-exclusion lock that owns the protected data T — impossible to access T without locking.
Notes & Pitfalls
- Protects the data directly (
Mutex<T>): You cannot touchTwithout acquiring theMutexGuard, which unlocks automatically onDrop. - Never hold a
std::sync::MutexGuardacross an.awaitpoint: Drop the guard before awaiting (or usetokio::sync::Mutexif the lock must span.await).
Example
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let total = Arc::new(Mutex::new(0));
let t = Arc::clone(&total);
thread::spawn(move || { *t.lock().unwrap() += 10; }).join().unwrap();
assert_eq!(*total.lock().unwrap(), 10);
}
Linked from
Related notes
- tuts/rust/std/sync/RwLock Linked here; links to this page; shared tags: #prog, #rust, #stdlib, #sync, #tier
- tuts/rust/std/sync Linked here; links to this page; shared tags: #prog, #rust, #stdlib, #sync
- tuts/rust/builtins Linked here; shared tags: #prog, #rust
- tuts/rust/tutorials/concurrent_worker_pool_channels links to this page; shared tags: #prog, #rust
- tuts/rust/std/sync/AtomicUsize shared tags: #prog, #rust, #stdlib, #sync, #tier
- tuts/rust/std/sync/mpsc shared tags: #prog, #rust, #stdlib, #sync, #tier
- tuts/rust/std/sync/OnceLock shared tags: #prog, #rust, #stdlib, #sync, #tier
- tuts/rust/std/collections/BinaryHeap shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/BTreeMap shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/HashMap shared tags: #prog, #rust, #stdlib, #tier