liveBook · Manning

Locking

As explained in Learn Rust in a Month of Lunches

Mutual exclusion is a concurrency property that allows at most one thread to access a protected resource at a time.

Locking provides mutual exclusion: at most one thread can access a protected resource at a time. In Rust, std::sync::Mutex provides this protection while still allowing a value to change through an otherwise immutable binding. section 10.3.3 section 10.3

use std::sync::Mutex;
 
fn main() {
    let my_mutex = Mutex::new(5);                       #1
 
    let mut mutex_changer = my_mutex.lock().unwrap();   #2
 
    println!("{my_mutex:?}");                           #3
 
    println!("{mutex_changer:?}");                      #4
 
    *mutex_changer = 6;   
 
     #5
    println!("{mutex_changer:?}");                      #6
}

Calling .lock().unwrap() returns a MutexGuard. Treat the guard like a locked door: while it exists, change the protected value through it. section 10.3.3

A simple locking workflow is:

  • Create a Mutex with the value it should protect. section 10.3.3
  • Call .lock() to obtain a MutexGuard, then change the value through the guard. section 10.3.3
  • Release the lock by letting the guard leave its scope or by passing it to drop(). section 10.3.3
  • Use .try_lock() when waiting indefinitely would be unsafe; it reports failure instead of blocking forever. section 10.3.3 section 10.4

Incrementing a protected value

A compact update is *my_mutex.lock().unwrap() += 1;. Repeating this in a loop locks the value for each update and releases the guard at the end of the statement. Holding a second lock on the same Mutex with .lock() can wait forever, causing a deadlock. section 10.3.3

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains guards, scope-based release, drop(), deadlock, and try_lock(), but not broader synchronization design.
Examples
Uses integer mutation, scoped guards, explicit drop(), repeated increments, and a deliberately blocking second lock.
What it assumes
Assumes basic Rust mutation and references while introducing thread-safe interior mutability from the ground up.
What you can do after
Apply it via Rust's std::sync::Mutex to guard shared updates and avoid indefinite waits with try_lock().
How it connects
Connects locking to interior mutability, MutexGuard, deadlocks, try_lock(), RefCell, and RwLock.

Also explained in

Compare how 18 books explain locking →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.