Skip to content
Theory · Threads · lesson 5 of 7

Mutex and Arc

A channel passes values from hand to hand. But sometimes several workers need the same thing: a shared counter, a shared order list. If two threads change one number at the same time with no order at all, one change can overwrite the other. This is called a data race, and safe Rust does not allow it.

In a workshop, shared things sit in a storeroom, and there is only one key to it. Whoever takes the key goes in and works with the shelves. The others wait at the door. On the way out, the worker returns the key, and the next one takes it.

Mutex: the one storeroom key

A mutex, the type Mutex<T>, hides a value inside. The only way to reach it is through lock() — that is "taking the key".

Rust
use std::sync::Mutex;

fn main() {
    let m = Mutex::new(5);
    {
        let mut g = m.lock().unwrap();
        *g += 1;
        println!("{g}"); // 6
    }
    println!("{}", m.lock().unwrap()); // 6
}

Let's go through the example line by line:

  1. Mutex::new(5) puts 5 into the storeroom.
  2. m.lock() takes the lock. The method takes &self, so m needs no mut. It returns a Result, and unwrap takes a guard out of it — a value of type MutexGuard.
  3. The value is read and changed through the guard: *g += 1, as through a mutable reference. We change the number through g, so g is declared with mut.
  4. println!("{g}") prints the value behind the guard: 6.
  5. At } the guard is dropped, and the lock is released by itself.
  6. The last line takes the lock again and prints 6.

Arc: a shared pass

The mutex has to be handed to several threads. But move moves a value into one closure, and the second thread gets nothing. You need a shared owner.

You already know Rc — a book with a reader count on its card. For threads it has a twin, Arc: a shared pass with a counter. Arc::clone(&m) does not copy the mutex; it issues one more pass to the very same one and adds 1 to the count. What sets Arc apart is that it changes the count with the processor's atomic operations: such a change happens in one indivisible step, and another thread cannot cut in halfway. So two threads cannot corrupt the count, even when they clone a pass at the same moment.

Each part answers its own question:

  • Arc — who owns the value;
  • Mutex — who is changing it right now.

Both types live in the module std::sync, and one line makes their names available: use std::sync::{Arc, Mutex}; — the curly braces list several names from one module.

When the lock is released

The main rule of a mutex: the lock is held while the guard is alive, and it is released by itself when the guard goes out of scope. Step through the program and watch two things: where the guard is now and what the second thread is waiting for.

LiveThe guard and the lockstep 1 of 14

Arc::clone issued a second pass to the same mutex; the lock is free.

Watch when the guard g is dropped and the thread gets the lock

So, step by step through the trace:

  1. The thread reached lock, but main had the key, and the thread waited.
  2. The lock was released not after the last use of g but at the block's closing brace, where the guard was dropped.
  3. Only then did the thread take the lock and see 1, not 0.

The practical lesson: keep a guard in a small block. While it is alive, the other threads stand at the door.

A counter in several threads

Let's put it all together: three threads add their 1, 2 and 3 to a shared number.

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

fn main() {
    let total = Arc::new(Mutex::new(0));
    let mut handles = Vec::new();
    for i in 1..=3 {
        let t = Arc::clone(&total);
        let h = thread::spawn(move || *t.lock().unwrap() += i);
        handles.push(h);
    }
    handles.into_iter().for_each(|h| h.join().unwrap());
    println!("{}", total.lock().unwrap()); // 6
}

What happens here:

  1. Each step of the loop gives a thread its own pass t to one and the same mutex.
  2. *t.lock().unwrap() += i takes the lock, adds i and lets go at once: the guard here is temporary and is dropped at the end of the line.
  3. i is a Copy value, so move puts a copy of it into the thread.
  4. The threads take the lock one at a time, and no addition is lost.
  5. for_each calls the closure for every item of the iterator — the same as a for h in handles loop. Here it calls join for each thread.
  6. The printing comes after every join, so the total is always 6.

Common mistake

The guard is declared without mut, and then the value is changed through it:

Rust
use std::sync::Mutex;

fn main() {
    let m = Mutex::new(5);
    let g = m.lock().unwrap(); // ✗
    *g += 1;
    println!("{g}");
}
TEXT
error[E0596]: cannot borrow `g` as mutable, as it is not declared as mutable

The program does not compile. m needs no mut, because lock takes &self. The guard does need mut: *g += 1 changes the value through it. The fix is let mut g = m.lock().unwrap();.

Key points

  • lock() takes &self and returns a MutexGuard; the value is read and changed through it.
  • The lock is released when the guard goes out of scope, not after its last use.
  • Arc::clone issues one more pass to the same value; Arc<Mutex<T>> gives threads a shared mutable counter.