std-type

Mutex: exclusive access to shared data

A mutex combines data with exclusive access. To change the value, acquire a guard. Keep related fields under one lock when their invariant must be maintained together. Expected stdout (not executed): 15 Common mistake: Keeping an unrelated lock for each half of a shared invariant.

Formal Syntax & Structure

rust syntaxrust
Mutex::new(value: T) -> Mutex<T>

Working Example

Example Snippetrust
fn main() {    use std::sync::Mutex;    let total = Mutex::new(10);    *total.lock().unwrap() += 5;    println!("{}", total.into_inner().unwrap());}
Rust Reference