Mutex<T>

Mutex<T> in Rust: The depot's cash box is not merely locked. The key does not exist separately from it: there is one key, on a short chain fixed to the lid,…

The Analogy: One Key, And It Is Attached To The Box

The depot's cash box is not merely locked. The key does not exist separately from it: there is one key, on a short chain fixed to the lid, and there is no way of getting at the contents without having taken hold of it. That sounds like a detail of ironmongery and it is actually the entire design. Nobody can be careless about remembering to lock up afterwards, because the box and its key are one object. If you have reached the contents, then you are holding the key, by definition rather than by discipline.

So the rule enforces itself. Whoever has the key has the box, and everyone else waits at the table until it comes back. In the ordinary case nobody waits long, because the key returns by itself when the clerk finishes -- they do not have to remember to hang it up, and they cannot wander off with it while doing something else, since doing something else means putting the box down.

Waiting is where it goes wrong, and it goes wrong without an error message. Suppose there are two boxes, petty cash and stamps, each with its own attached key. One clerk takes the petty-cash key and then reaches for the stamps key. Another takes the stamps key and then reaches for petty cash. Both of them now sit at that table for the rest of the afternoon. Neither has done anything wrong that you could point at in their own paperwork; the fault is only in the order they reached for things, and the order is not written down anywhere.

Then there is the clerk who is taken ill with the box open, coins on the table and the ledger half-written. The next person to ask for the key does not simply get handed it. They are told what happened first, because the contents may now be in a state nobody intended, and passing the box along as though the afternoon had gone normally would turn one accident into a discrepancy that nobody could ever trace back.


Syntax or Core Structure

A Mutex does not sit next to the data it protects. It contains it.

use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let tally = Arc::new(Mutex::new(0u32));
    let mut handles = Vec::new();

    for bay in 1..=4 {
        let tally = Arc::clone(&tally);

        handles.push(thread::spawn(move || {
            for _ in 0..1000 {
                let mut n = tally.lock().unwrap();

                *n += bay;
            }
        }));
    }

    for handle in handles {
        handle.join().unwrap();
    }

    println!("handles {}", Arc::strong_count(&tally));
    println!("tally   {}", *tally.lock().unwrap());
}

Output:

handles 1
tally   10000

Four thousand increments from four threads, and the answer is the arithmetic answer. The type is Mutex<u32>, not a u32 beside a Mutex, so there is no expression anywhere in the language that reads or writes that number without going through lock. Forgetting to take the lock is not a bug you can write.

lock() returns a MutexGuard that derefs to the value -- *n += bay is writing through it -- and unlocks when it drops, which here is at the end of each loop iteration. The Arc is doing the same job Rc did in this module's second lesson, with atomic reference counts so that it is Send and Sync; an Rc here does not compile, and that refusal is the compiler catching a data race before the program exists. And handles 1 at the end confirms the four clones were dropped with their threads.

What it does
Mutex::new(v)Wraps v so that it can only be reached by locking
m.lock()Waits until the lock is free, then yields a Result containing a guard
the guardDerefs to T, and unlocks the instant it is dropped
Arc::new(m)Shared ownership across threads, counted atomically
Arc::clone(&a)One more owner. Cheap, but an atomic increment rather than free
m.try_lock()Returns straight away, with Err if the lock is currently held

Technical Depth: The Two Ways It Bites

Why lock returns a Result

use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let ledger = Arc::new(Mutex::new(vec![118, 124]));
    let doomed = Arc::clone(&ledger);

    let handle = thread::spawn(move || {
        let mut rows = doomed.lock().unwrap();

        rows.push(7);

        panic!("bay door jammed");
    });

    println!("worker failed {}", handle.join().is_err());
    println!("poisoned      {}", ledger.is_poisoned());
    println!("plain lock    {}", ledger.lock().is_err());

    let recovered = match ledger.lock() {
        Ok(rows) => rows.clone(),
        Err(poisoned) => poisoned.into_inner().clone(),
    };

    println!("recovered     {recovered:?}");
}

Output. The failing thread also writes its panic message to stderr; only the four stdout lines are shown:

worker failed true
poisoned      true
plain lock    true
recovered     [118, 124, 7]

A thread that panics while holding a lock poisons it, and every later lock() returns Err. The data is perfectly intact in this example -- the push finished before the panic -- but the mutex has no way of knowing that, and that is the point. A lock exists to protect an invariant across several steps, and a panic in the middle of those steps means the invariant may not hold. Poisoning converts "this may be nonsense" into something the next thread is told rather than something it discovers later.

PoisonError::into_inner hands over the guard anyway, for when you know the data is still sound. Which makes the ubiquitous .unwrap() after lock() a decision and not boilerplate: it says "if another thread died holding this, I would rather die too than carry on with data of unknown validity". That is usually the right call. It should still be a call you made.

The failure with no error message

use std::sync::{Arc, Mutex};
use std::thread;

fn transfer(from: &Mutex<u32>, to: &Mutex<u32>, amount: u32) {
    let mut a = from.lock().unwrap();
    let mut b = to.lock().unwrap();

    *a -= amount;
    *b += amount;
}

fn main() {
    let petty = Arc::new(Mutex::new(500u32));
    let stamps = Arc::new(Mutex::new(100u32));

    let p = Arc::clone(&petty);
    let s = Arc::clone(&stamps);
    let one = thread::spawn(move || transfer(&p, &s, 50));

    let p = Arc::clone(&petty);
    let s = Arc::clone(&stamps);
    let two = thread::spawn(move || transfer(&p, &s, 20));

    one.join().unwrap();
    two.join().unwrap();

    println!("petty  {}", *petty.lock().unwrap());
    println!("stamps {}", *stamps.lock().unwrap());
}

Output:

petty  430
stamps 170

Both threads take petty first and stamps second, so this always works. Change the second one to transfer(&s, &p, 20) and the two threads now acquire the same pair of locks in opposite orders. Most runs will still print the right numbers, which is the genuinely dangerous part. Occasionally the first thread holds petty and waits for stamps while the second holds stamps and waits for petty, and both wait for the rest of time: no panic, no error, no timeout, nothing in the output, just a process that has stopped making progress while looking entirely healthy.

There is no clever fix, only a rule: every path through the program takes locks in one fixed order, and that order is written down where the locks are declared. Related trap, same cause -- a Mutex is not re-entrant, so a thread that locks one it already holds deadlocks with itself. That most often happens when a method that takes the lock calls another method that also takes it.

RefCell<T>Mutex<T>
A conflicting access gives youAn immediate panicA wait, possibly for ever
When you find outThe first time the paths crossPossibly never, during testing
Across threadsNot allowed, and the compiler says soThe entire purpose
Cost per accessA counterAn atomic operation, and a syscall when contended
Re-entrantNo -- it panicsNo -- it deadlocks

The cheaper relatives

use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Arc, RwLock};
use std::thread;

fn main() {
    let hits = Arc::new(AtomicU32::new(0));
    let table = Arc::new(RwLock::new(vec![118, 124, 7]));
    let mut handles = Vec::new();

    for _ in 0..4 {
        let hits = Arc::clone(&hits);
        let table = Arc::clone(&table);

        handles.push(thread::spawn(move || {
            let rows = table.read().unwrap();

            hits.fetch_add(rows.len() as u32, Ordering::Relaxed);
        }));
    }

    for handle in handles {
        handle.join().unwrap();
    }

    table.write().unwrap().push(131);

    println!("hits  {}", hits.load(Ordering::Relaxed));
    println!("rows  {}", table.read().unwrap().len());
}

Output:

hits  12
rows  4

All four read() locks can be held simultaneously, which is what RwLock buys: many readers or one writer, decided at run time. It is to Mutex what RefCell's two kinds of borrow are to a single guard, and it is only a win when reads genuinely dominate -- otherwise the extra bookkeeping costs more than it saves.

AtomicU32 is the other direction, and it stands to Mutex<u32> exactly as Cell stands to RefCell: no guard, no poisoning, nothing to block on, and no critical section at all, in exchange for only working on values the hardware can update in a single instruction. Ordering::Relaxed is the right choice for a counter that nothing else is ordered against, and choosing between the orderings for anything more involved is a genuinely deep subject that starts where this lesson stops.


Real World Example: A Queue Three Workers Can All Pull From

This is the shape a channel cannot give you, and the reason is one word in mpsc.

use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::thread;

struct Job {
    bay: &'static str,
    minutes: u32,
}

struct Done {
    worker: usize,
    bay: &'static str,
    pence: u32,
}

fn main() {
    let queue = Arc::new(Mutex::new(vec![
        Job { bay: "a-01", minutes: 20 },
        Job { bay: "a-02", minutes: 90 },
        Job { bay: "b-01", minutes: 15 },
        Job { bay: "b-02", minutes: 45 },
        Job { bay: "c-01", minutes: 30 },
        Job { bay: "c-02", minutes: 5 },
    ]));

    let results = Arc::new(Mutex::new(Vec::new()));
    let taken = Arc::new(AtomicUsize::new(0));
    let mut handles = Vec::new();

    for worker in 0..3 {
        let queue = Arc::clone(&queue);
        let results = Arc::clone(&results);
        let taken = Arc::clone(&taken);

        handles.push(thread::spawn(move || {
            loop {
                let job = {
                    let mut q = queue.lock().unwrap();

                    q.pop()
                };

                match job {
                    Some(job) => {
                        taken.fetch_add(1, Ordering::Relaxed);

                        let raw = job.minutes * 6;
                        let pence = if raw < 300 { 300 } else { raw };

                        results.lock().unwrap().push(Done {
                            worker,
                            bay: job.bay,
                            pence,
                        });
                    }
                    None => break,
                }
            }
        }));
    }

    for handle in handles {
        handle.join().unwrap();
    }

    let remaining = queue.lock().unwrap().len();
    let mut done = results.lock().unwrap();

    done.sort_by_key(|d| d.bay);

    for d in done.iter() {
        println!("{:5}  {:4}", d.bay, d.pence);
    }

    let total: u32 = done.iter().map(|d| d.pence).sum();
    let sane = done.iter().all(|d| d.worker < 3);

    println!("jobs   {}", done.len());
    println!("taken  {}", taken.load(Ordering::Relaxed));
    println!("total  {total}");
    println!("queue  {remaining}");
    println!("range  {sane}");
}

Output:

a-01    300
a-02    540
b-01    300
b-02    300
c-01    300
c-02    300
jobs   6
taken  6
total  2040
queue  0
range  true

The word is "single-consumer". Three workers cannot take from one mpsc::Receiver, but anybody holding the lock can pop a Mutex<Vec<Job>>, so a shared work queue is about eight lines of code. Two locks and one atomic, each behind an Arc so that all three threads own them, and no thread ever needs to know how many others exist.

The block around the pop is the most important thing in this program. The lock is taken, one job comes out, the guard dies at the closing brace, and only then is any work done. Write it the obvious way -- while let Some(job) = queue.lock().unwrap().pop() -- and the guard from the scrutinee stays alive for the entire body, exactly as it would in a RefCell. The queue would then be held locked while each price is computed and while results is locked, which flattens three threads back into one and nests two locks in an order nobody chose. Same rule as the previous lesson, different punishment: there, holding a guard too long panics and tells you; here it silently deletes your parallelism and reports success.

The output is deterministic on purpose, and what is missing from it is as deliberate as what is in it. Which worker got which job is never printed, because it is not reproducible -- run this on another machine and the split changes. Everything worth asserting is reproducible: six jobs done, six taken, the queue empty, the total 2040, every recorded worker id in range. taken is an AtomicUsize rather than a third Mutex because incrementing a counter needs no critical section, and Relaxed is the honest ordering for a number that nothing else is sequenced against.

The limits, and the last one is the real one. Three workers on six trivial jobs is slower than one worker, worse here than in the threads lesson because they also contend for the same two locks. The Vec is popped from the end, so this is a stack wearing the word "queue", and that is only acceptable because nothing depends on order. A worker has no way to report a failure: a panic poisons whichever lock it was holding, and join().unwrap() in main would then turn one bad job into a dead program with a stderr message and no report. And the shutdown condition is "the queue was empty when I looked", which is simply wrong as soon as jobs can arrive while work is in progress -- the first worker to find it empty leaves for good. Fixing that properly needs a condition variable, and that is the next thing to read after this course.


Common Mistakes

  1. Holding the guard while doing the work. The lock should cover getting the value out and putting the result back, not the computation in between. This is the mistake that makes a threaded program slower than the single-threaded one it replaced.
  1. Taking two locks in different orders on different paths. Classic deadlock, and it usually passes every test you write. One documented lock order, everywhere, no exceptions.
  1. Locking the same mutex twice in one thread. It is not re-entrant, so it deadlocks with itself. Almost always arrives via a locking method that calls another locking method.
  1. Rc<Mutex<T>>. It will not compile across threads, because Rc is not Send, and the error tends to name Send on some enclosing type instead. Arc is the fix.
  1. Arc<T> on its own and then trying to mutate. Arc gives shared ownership, never mutable access. Arc<Mutex<T>> is the pair, exactly as Rc<RefCell<T>> was in the single-threaded case.
  1. Treating lock().unwrap() as noise. It is a decision about poisoning. Make it once, knowingly, and write down why.
  1. A Mutex<u32> for a counter. An atomic does the same job with no guard, no poisoning and no blocking.
  1. Assuming RwLock is the faster Mutex. It has more bookkeeping, and it only wins when reads heavily dominate. Measure it.
  1. Wrapping a whole struct when one field is shared. Every reader of every field then queues behind every writer of the one field that needed protecting.

Best Practices

  • Keep critical sections as small as they will go. Pull the value out inside a block, let the guard drop, then compute.
  • Write the lock order down next to the declarations and take them in that order everywhere. This is the only reliable defence against deadlock.
  • Use atomics for counters and flags, and a Mutex for anything with an invariant spanning more than one field.
  • Put the Arc<Mutex<...>> around the smallest thing that is genuinely shared, not around the object that happens to contain it.
  • Decide about poisoning deliberately: unwrap when carrying on would be worse, into_inner when you can show the data is still sound.
  • Never call code you do not control -- a callback, a trait method, a closure a caller handed you -- while holding a lock. You cannot know whether it locks something too.
  • Use channels to hand work over and mutexes for state that is genuinely shared. Reach for a mutex specifically when several threads must consume from one place.
  • Measure before reaching for RwLock or atomics as optimisations. A plain Mutex around a small critical section is fast, and it is much harder to get wrong.

Practice Exercises

  1. Rewrite the worker loop as while let Some(job) = queue.lock().unwrap().pop(), then add a print inside the critical section showing which worker holds the lock. Explain from that output why the parallelism disappeared.
  1. Change one of the two threads in the transfer example to take the locks in the opposite order and run it a few hundred times in a loop. Describe what you observe, and explain why runs that succeeded are not evidence that the code is correct.
  1. Make a worker panic while holding the results lock. Confirm the lock is poisoned, recover the results with into_inner, and state precisely which part of the report you can no longer trust.
  1. Replace Mutex<Vec<Done>> with a channel back to main. Say which of the two locks you were able to delete, which one you could not, and what that tells you about when to use each.