Skip to content
Tutorials Center
My learning

Topics

Lesson 77 of 132 ยท Concurrency

Shared State: Mutex and RwLock

Learn shared-state concurrency in Rust: Arc<Mutex<T>>, lock guards, poisoning, try_lock and deadlocks, RwLock, Condvar, Barrier and how to avoid lock contention.

Message passing with channels is a fine way to coordinate threads, but sometimes the natural design is simply "many threads need to read and update the same piece of data": a cache, a counter, a table of results. Rust allows this, but it makes you ask for it explicitly. A plain &mut T can only be held by one thread, and a plain &T promises that nobody changes the value. To get shared mutable data you need a type that enforces exclusive access at run time. The most common one is Mutex<T>.

A mutex (short for mutual exclusion) wraps a value and allows only one thread at a time to touch it. To use the value you first lock the mutex, which waits if another thread holds the lock, and you get back a guard. While the guard exists you have exclusive access; when the guard is dropped, the lock is released. In this lesson you will combine Arc and Mutex, see why the lock lives inside the data, learn about poisoning and deadlocks, and then meet RwLock, Condvar and Barrier.

Our editor has one CPU and a 5 second limit. We always join threads before printing results, and we say so whenever an order is not guaranteed.

Mutex on its own

In many languages the lock is a separate object and you must remember to take it before touching the data. In Rust the data is inside the mutex, so you cannot reach it without locking. That makes forgetting the lock a compile error instead of a bug.

Rust Locking a Mutex

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

lock() returns Result<MutexGuard<T>, PoisonError<...>>. We unwrap it to keep the demo short; poisoning is explained below. The guard implements Deref and DerefMut, so *guard += 1 changes the number inside. The guard also implements Drop: the lock is released at the end of the scope, even if the code leaves early with return, ? or a panic. This is the RAII idea at work, and it is why Rust has no unlock() method.

A guard held longer than necessary is the number one cause of slow lock-based code, so keep its scope small: lock, do the quick update, let go.

Arc<Mutex>: sharing between threads

A Mutex by itself lives in one place, and threads started with thread::spawn need to own what they use. Wrapping it in an Arc (an atomically reference-counted pointer, see Rc and Arc) lets each thread own a handle to the same mutex.

Rust Eight threads, one counter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Every run prints exactly total = 8000. Without the mutex the threads would sometimes read the same old value and lose updates. The shadowed name let counter = Arc::clone(&counter); inside the loop is a common idiom: each iteration makes a new handle that is moved into that iteration's thread. When a thread finishes, its Arc is dropped, so the strong count is back to 1 after the joins.

Arc::clone copies only the pointer and bumps a counter; the mutex and its number are never duplicated. If you wrote counter.clone() on the inner data instead of the Arc, you would get independent copies and each thread would update its own number.

What if you forget the Arc and try to move a plain Mutex into several threads? The compiler stops you:

Rust A Mutex moved into many threads (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The first iteration moves counter into the closure, so the second iteration has nothing left to move. rustc reports error[E0382]: use of moved value: `counter` . The cure is exactly the Arc clone from the previous example.

What the guard protects

A guard gives you a real &mut T, so everything you know about borrowing applies. A mutex around a Vec or a HashMap is a perfectly good shared collection:

Rust A shared log with Mutex<Vec>

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

We sort before printing because we cannot know which thread locked first. Sorting (or collecting into a BTreeMap) is the standard trick for making concurrent output deterministic.

Notice a design rule in action: the mutex guards the whole Vec, so any invariant between its elements stays consistent. Many small mutexes inside one structure are harder to get right than a single mutex around a single piece of state.

Poisoning

If a thread panics while it holds a guard, the data might be half updated. Rust marks the mutex as poisoned, and later calls to lock() return Err. This is why lock() returns a Result.

Rust A poisoned mutex

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The panic message goes to stderr (it appears under the output). PoisonError::into_inner hands you the guard anyway, which is the right move when the data cannot really be corrupted (a counter, a cache). In most application code, lock().unwrap() is acceptable: if another thread died while holding the lock, propagating the panic is often the safest reaction. If you do want to ignore poison, lock().unwrap_or_else(|e| e.into_inner()) is the idiom.

try_lock and deadlocks

lock() blocks. If a thread waits for a lock that it will never receive, you have a deadlock. The classic recipe uses two locks taken in opposite order by two threads: thread A holds lock 1 and waits for lock 2, thread B holds lock 2 and waits for lock 1. Locking the same mutex twice in one thread is also a deadlock (or a panic, the behaviour is unspecified).

We cannot demonstrate a real deadlock without freezing the program, but try_lock lets us see the situation safely. It returns immediately with Err(WouldBlock) when the lock is taken.

Rust try_lock shows a lock is held

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rules that keep real programs deadlock-free:

  • Hold as few locks as possible, for as short a time as possible.
  • If you must take two locks, always take them in the same global order (for example by ascending id).
  • Never call unknown code (callbacks, trait methods you do not control) while holding a lock.
  • Never hold a guard across a blocking call such as I/O or join().
  • Do not lock the same mutex again inside a function you called with the guard still alive. Pass the guard or the inner &mut T down instead.

The compiler prevents data races, not deadlocks. A program with a deadlock is perfectly safe Rust; it just never finishes.

Guard lifetimes and temporaries

Because the guard is dropped at the end of its scope, where the scope ends matters. A temporary guard in an expression statement lives until the semicolon:

Rust
*counter.lock().unwrap() += 1; // locked and released within this statement

But in if let, match and while let conditions in older editions, a temporary guard could live to the end of the whole block, which surprised many people. Edition 2024 changed if let so temporaries are dropped before the else branch, but a match scrutinee still keeps its temporaries until the end of the match. The safe habit is to copy what you need into a local variable first and let the guard go:

Rust Dropping the guard early

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

If the second lock() were inside a match queue.lock().unwrap().pop() { ... }, the first guard would still be alive and the program would deadlock. Splitting the statement is the easy fix.

RwLock: many readers or one writer

A Mutex lets only one thread in, even if all of them only want to read. RwLock<T> distinguishes the two: any number of threads may hold a read guard (read()) at the same time, or exactly one thread may hold the write guard (write()).

Rust RwLock with readers and a writer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

When is RwLock worth it? When reads vastly outnumber writes and holding the lock takes a while. For tiny critical sections a plain Mutex is often faster, because an RwLock has more bookkeeping. An RwLock can also be subject to writer starvation or reader starvation, depending on the operating system's policy, so do not assume fairness. And just like a Mutex, a thread that holds a read guard and then asks for the write lock on the same RwLock will deadlock.

Condvar: waiting for a condition

Sometimes a thread must wait until something changes (a queue gets an item, a flag turns true). Looping and calling lock() over and over wastes CPU. A condition variable, Condvar, lets a thread sleep until another thread signals it. It is always paired with a Mutex that holds the state being waited on.

Rust Condvar: wait until the flag is set

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

cvar.wait(guard) atomically releases the lock and sleeps; when woken it re-acquires the lock and hands the guard back. Two rules matter. First, check the condition in a while loop: the operating system may wake a thread without a notification (a spurious wake-up), and the condition may have changed again before you got the lock. Second, change the state while holding the mutex, then notify. Condvar::wait_while(guard, |ready| !*ready) wraps the loop for you.

The worker's println! always appears first only because the main thread could not proceed without the flag; if both prints can race, say so in your own programs or print after the joins.

Barrier: everyone meets here

A Barrier makes a group of threads wait for each other, which is handy for phases ("everyone finish loading, then everyone start computing"). wait() returns a BarrierWaitResult whose is_leader() is true for exactly one thread per round.

Rust A Barrier between two phases

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The AtomicUsize is explained in the next lesson, Atomics. Here it is just a lock-free counter.

Avoiding contention

A lock that many threads fight over turns a parallel program into a sequential one with extra overhead. Some practical remedies, roughly from best to worst:

  1. Do not share. Give each thread its own data and combine the results at the end, as in the thread-per-chunk examples in Threads.
  2. Shrink the critical section. Compute outside the lock; lock only to store the result.
  3. Shard the lock. Instead of one Mutex<HashMap>, use an array of mutexes and pick one by hash(key) % N.
  4. Use atomics for a single counter or flag (Atomics).
  5. Switch to message passing (channels) so one thread owns the data.
Rust Local sums, one lock at the end

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The version that locked for every single number would take the lock 100,000 times. This one takes it four times. For a data-parallel job like this, scoped threads are even simpler because they can borrow the slice with no Arc at all.

Mutex or RefCell?

Mutex<T> is to threads what RefCell<T> is to a single thread: interior mutability with a run-time check (RefCell and Cell). The difference is that RefCell panics when the rules are broken, while Mutex blocks until it is safe. Rust's type system keeps the two apart: RefCell is not Sync, so Arc<RefCell<T>> cannot cross threads. Send and Sync explains how.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does Mutex<T> in Rust wrap the data instead of being a separate lock object?

    The data lives inside the mutex and is only reachable through the guard that lock() returns, so a thread cannot touch it without holding the lock.
  2. 2. When is the lock of a MutexGuard released?

    The guard implements Drop. There is no unlock() method; the lock is released when the guard goes out of scope or is passed to drop.
  3. 3. What does a poisoned mutex mean?

    Poisoning records that a holder panicked. lock() returns Err(PoisonError), and into_inner() still gives you access to the data if you decide to trust it.
  4. 4. Which situation is the best fit for RwLock rather than Mutex?

    RwLock allows many simultaneous readers. For short critical sections or write-heavy data a Mutex is usually as fast or faster, and neither lock type prevents deadlocks.
  5. 5. Why must a Condvar wait be placed in a while loop?

    A thread may wake without a notification, and the condition may change again before it re-acquires the lock, so it must test the condition in a loop (or use wait_while).

Summary

  • Mutex<T> stores the data inside the lock; lock() returns a guard that gives exclusive access and unlocks on drop.
  • Share a mutex between threads with Arc<Mutex<T>>; clone the Arc, not the data.
  • Keep guards short-lived, and never hold one across blocking calls or while calling unknown code.
  • A panic while locked poisons the mutex; into_inner() recovers the guard if you trust the data.
  • try_lock never blocks; take multiple locks in a consistent order to avoid deadlocks, which the compiler does not prevent.
  • RwLock allows many readers or one writer; Condvar waits for a condition (always in a loop); Barrier synchronizes phases.
  • Reduce contention by sharing less: local work, short critical sections, sharding, atomics or channels.

Next: Atomics and Memory Ordering