Blog

Part 24 · Shared State and Channels in Rust: Arc, Mutex, mpsc and Atomics

Threads that change one value need a lock or an atomic, and threads that hand work to each other need a channel. This part shows Arc with Mutex, RwLock, AtomicUsize and mpsc, and makes a deadlock happen on purpose.

In Part 23, our threads owned their data, borrowed it read-only, or split it into pieces. Sometimes that isn’t enough. Four threads all want to add to one counter, or several workers want to hand results to one collector. This part covers both: shared state, where threads change one value under a lock, and channels, where threads send values to each other.

We’ll use Arc with Mutex, then RwLock and the atomic types, then std::sync::mpsc channels. At the end we make two threads deadlock on purpose, in a way that ends every time, and fix it. It builds on Rc from Part 20 and threads from Part 23. Every program here was run on Rust 1.95, and its output is pasted from the run.

Try this first

Four threads each add 1 to a shared counter a thousand times. Arc is the thread-safe Rc from Part 23, so every thread can own a handle to the same number. Will this compile, and if it does, what’s the total?

use std::sync::Arc;
use std::thread;

fn main() {
    let counter = Arc::new(0);
    let mut handles = Vec::new();
    for _ in 0..4 {
        let counter = Arc::clone(&counter);
        handles.push(thread::spawn(move || {
            for _ in 0..1000 {
                *counter += 1;
            }
        }));
    }
    for h in handles {
        h.join().unwrap();
    }
    println!("total: {counter}");
}

It doesn’t compile:

error[E0594]: cannot assign to data in an `Arc`
  --> src/main.rs:11:17
   |
11 |                 *counter += 1;
   |                 ^^^^^^^^^^^^^ cannot assign
   |
   = help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `Arc<i32>`

Arc solves the “who owns it” half of the problem. Four threads can each hold an Arc, and the number lives until the last one is dropped. But an Arc only hands out shared access, like &. It never gives you &mut, because four threads could ask for it at once. If you call a method that needs &mut, such as push on an Arc<Vec<i32>>, you get the same message with a different code, E0596: “cannot borrow data in an Arc as mutable”.

To change the number, we need something that lets one thread at a time in. That’s a lock.

Arc plus Mutex

A Mutex<T> (“mutual exclusion”) wraps a value and lets one thread at a time reach it. You can’t touch the value without asking first. Put the mutex inside an Arc, and every thread can own a handle to the same lock:

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

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

    for _ in 0..4 {
        let counter = Arc::clone(&counter);
        handles.push(thread::spawn(move || {
            for _ in 0..1000 {
                let mut n = counter.lock().unwrap();
                *n += 1;
            }
        }));
    }

    for h in handles {
        h.join().unwrap();
    }
    println!("total: {}", *counter.lock().unwrap());
    println!("Arc owners left: {}", Arc::strong_count(&counter));
}

It prints:

total: 4000
Arc owners left: 1

We ran this 20 times, and it printed 4000 every time. The threads ran in a different order each run, but no update was lost.

Each of the two types does one job:

  • Arc answers “who owns it?” Five owners here: main and four threads. As each thread ends, its Arc is dropped, and by the last line only main‘s is left.
  • Mutex answers “who may change it right now?” Exactly one thread, the one holding the lock.

counter.lock() waits until no other thread holds the lock, then takes it. It returns a Result, and we’ll see the Err case under “Lock poisoning” below. The Ok value is a MutexGuard, and the guard is what gives you access: it works like &mut i32, so *n += 1 changes the number inside.

If the threads only need to run inside one function, the scoped threads from Part 23 can borrow a plain Mutex without the Arc. We’ll do that later in this part. Arc is for threads made with thread::spawn, which may outlive the function that started them.

The guard holds the lock

There’s no unlock method. The lock is released when the guard is dropped. That’s the Drop mechanism from Part 6 doing a new job. try_lock lets us see it. It’s like lock, but instead of waiting it returns an error at once if the lock is taken:

use std::sync::Mutex;

fn main() {
    let scores = Mutex::new(vec![10, 20]);

    let mut guard = scores.lock().unwrap();
    guard.push(30);
    println!("guard alive, locked: {}", scores.try_lock().is_err());

    drop(guard);
    println!("after drop(guard), locked: {}", scores.try_lock().is_err());

    {
        let mut guard = scores.lock().unwrap();
        guard.push(40);
    }
    println!("after the block, locked: {}", scores.try_lock().is_err());

    let len = scores.lock().unwrap().len();
    println!("one-line lock, locked: {}", scores.try_lock().is_err());
    println!("{len} scores: {:?}", scores.lock().unwrap());
}

It prints:

guard alive, locked: true
after drop(guard), locked: false
after the block, locked: false
one-line lock, locked: false
4 scores: [10, 20, 30, 40]

There are three ways to end a guard, and all three show up in real code:

  1. drop(guard) releases the lock on that line.
  2. A block releases it at the closing }. This is the usual way to keep a lock short.
  3. A temporary. In scores.lock().unwrap().len(), the guard is never given a name. It’s dropped at the end of the statement, so the lock is held for exactly one line.

While one thread holds the guard, every other thread that calls lock waits. So hold it for as little time as you can. Take the lock, read or change the value, and let go. Don’t keep it while you do slow work, such as reading a file or sleeping. In the counter above, the guard n lives for one pass of the inner loop, so the lock is taken and released 4000 times. That’s fine: an uncontended lock is cheap.

Lock poisoning

What if a thread panics while it holds the lock? It might have changed half of the value and left it broken. Rust marks the mutex as poisoned, and from then on lock returns Err:

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

fn main() {
    let balance = Arc::new(Mutex::new(100));

    let b = Arc::clone(&balance);
    let result = thread::spawn(move || {
        let mut guard = b.lock().unwrap();
        *guard -= 30;
        panic!("bank thread failed halfway");
    })
    .join();
    println!("thread finished ok: {}", result.is_ok());

    match balance.lock() {
        Ok(guard) => println!("balance: {}", *guard),
        Err(poisoned) => {
            println!("the mutex is poisoned");
            let guard = poisoned.into_inner();
            println!("the value inside is still there: {}", *guard);
        }
    }
}

It prints (the thread’s panic message goes to stderr first, and we’ve left it out):

thread finished ok: false
the mutex is poisoned
the value inside is still there: 70

The panic dropped the guard, so the lock was released. But the mutex remembers that its holder panicked. The Err is a warning: “the last writer didn’t finish, check this value before you trust it”. into_inner gives you the guard anyway, if you know the value is still sound.

That’s why lock().unwrap() is everywhere in Rust code. It means “if another thread panicked while holding this, panic here too”. For most programs that’s the right answer, because a panic is already a bug.

RwLock: many readers or one writer

A Mutex lets one thread in, even when every thread only wants to read. RwLock follows the rule from Part 7 instead: many readers or one writer. read() returns a guard that works like &T, and write() returns one that works like &mut T:

use std::sync::RwLock;
use std::thread;

fn main() {
    let price = RwLock::new(100);

    {
        let r1 = price.read().unwrap();
        let r2 = price.read().unwrap();
        println!("two readers at once: {} {}", *r1, *r2);
        println!("can a writer get in? {}", price.try_write().is_ok());
    }

    *price.write().unwrap() += 5;

    let seen: Vec<i32> = thread::scope(|s| {
        let handles: Vec<_> = (0..3).map(|_| s.spawn(|| *price.read().unwrap())).collect();
        handles.into_iter().map(|h| h.join().unwrap()).collect()
    });
    println!("readers saw: {seen:?}");
}

It prints:

two readers at once: 100 100
can a writer get in? false
readers saw: [105, 105, 105]

Two read guards lived at once, and a writer couldn’t get in until both were gone. This program uses a scoped thread, so the three readers borrow price directly, with no Arc.

Use RwLock when reads are common, writes are rare, and each read takes a while. For a small value read briefly, a Mutex is simpler and often just as fast. Whether a waiting writer goes ahead of new readers depends on the operating system; the standard library doesn’t promise either way.

Atomics: a counter without a lock

For a single number, there’s something lighter than a lock. The types in std::sync::atomic, such as AtomicUsize, AtomicI32 and AtomicBool, can be changed through a shared reference, using CPU instructions that can’t be interrupted halfway. fetch_add adds to the number and returns the old value, as one step:

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

fn main() {
    let hits = Arc::new(AtomicUsize::new(0));
    let mut handles = Vec::new();

    for _ in 0..4 {
        let hits = Arc::clone(&hits);
        handles.push(thread::spawn(move || {
            for _ in 0..1000 {
                hits.fetch_add(1, Ordering::Relaxed);
            }
        }));
    }

    for h in handles {
        h.join().unwrap();
    }
    println!("hits: {}", hits.load(Ordering::Relaxed));
}

It prints:

hits: 4000

There’s no guard and no unwrap. fetch_add takes &self, so the Arc is enough.

Every atomic operation takes an Ordering. It answers a different question from “is this add safe?” Every ordering makes the add itself atomic, so no update is lost. The ordering says what other memory writes the threads must agree on around the operation. Relaxed promises nothing about other memory, and that’s fine here, because the counter is all we share. The join calls also make sure main sees every thread’s work before it reads the total.

When an atomic guards other data, for example a flag that says “the buffer is ready”, Relaxed isn’t enough, and you need Acquire and Release. That’s a deep topic. The Ordering docs and the Rustonomicon’s chapter on atomics explain it properly. For a plain counter or a statistic, Relaxed is the right choice. For anything more, use a Mutex until you’ve read those pages.

Channels: send values instead of sharing them

A lock lets threads share one value. A channel lets them pass values to each other instead. One end sends, the other receives, and each value has one owner at a time: the sender gives it up and the receiver takes it.

std::sync::mpsc::channel() returns a pair: a Sender (tx) and a Receiver (rx). “mpsc” stands for “multiple producer, single consumer”. You can clone the sender as many times as you like, but there’s one receiver:

use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();

    for id in 1..=3 {
        let tx = tx.clone();
        thread::spawn(move || {
            for job in 1..=2 {
                tx.send(format!("worker {id} finished job {job}")).unwrap();
            }
        });
    }
    drop(tx);

    for message in rx {
        println!("{message}");
    }
    println!("all senders are gone, the loop ended");
}

It prints, in a different order on different runs:

worker 1 finished job 1
worker 1 finished job 2
worker 2 finished job 1
worker 2 finished job 2
worker 3 finished job 1
worker 3 finished job 2
all senders are gone, the loop ended

Each worker gets its own clone of tx. send moves the String into the channel, and for message in rx takes the messages out, one at a time, as they arrive. When the channel is empty, the loop waits for the next one.

So how does the loop know when to stop? It ends when the channel is empty and every Sender has been dropped. Then nobody could ever send again. Each worker’s clone is dropped when its thread ends. And the original tx, the one we cloned from, is dropped by drop(tx).

The loop that never ends

Take out drop(tx), and the program prints all six lines and then hangs. The workers are finished, but main still owns the original tx. As far as the channel knows, main might still send something, so the for loop waits forever.

We can’t paste the output of a program that never ends, but try_recv shows the difference. It’s like recv, but it never waits:

use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();

    let handles: Vec<_> = (1..=2)
        .map(|id| {
            let tx = tx.clone();
            thread::spawn(move || tx.send(id).unwrap())
        })
        .collect();
    for h in handles {
        h.join().unwrap();
    }

    let mut got: Vec<i32> = rx.try_iter().collect();
    got.sort();
    println!("received: {got:?}");
    println!("next, with tx alive:   {:?}", rx.try_recv());

    drop(tx);
    println!("next, after drop(tx):  {:?}", rx.try_recv());
}

It prints:

received: [1, 2]
next, with tx alive:   Err(Empty)
next, after drop(tx):  Err(Disconnected)

Both workers have finished, and both messages have arrived. With tx still alive, the channel says Empty: nothing now, but maybe later. A for loop or recv would wait at that point. After drop(tx), it says Disconnected: nothing now, and nothing ever. That’s the answer that ends a for loop. We sort got because the two threads may send in either order.

A bounded channel pushes back

channel() has no limit. If the producers are faster than the consumer, messages pile up in memory. sync_channel(n) holds at most n messages. When it’s full, send waits until the receiver takes one. That waiting is called backpressure: a slow consumer slows the producers down instead of letting work pile up.

use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::sync_channel(2);

    for n in 1..=3 {
        println!("try_send({n}): {:?}", tx.try_send(n));
    }
    println!("got {}", rx.recv().unwrap());
    println!("try_send(4): {:?}", tx.try_send(4));

    let producer = thread::spawn(move || {
        for n in 5..=8 {
            tx.send(n).unwrap();
        }
    });

    let rest: Vec<i32> = rx.iter().collect();
    producer.join().unwrap();
    println!("rest, in order: {rest:?}");
}

It prints:

try_send(1): Ok(())
try_send(2): Ok(())
try_send(3): Err(TrySendError::Full(..))
got 1
try_send(4): Ok(())
rest, in order: [2, 4, 5, 6, 7, 8]

The first half runs on one thread. try_send fails at once instead of waiting, so we can see the limit: two values fit, and the third is refused with Full. Once rx.recv() takes one out, there’s room again. In the second half, the producer’s send waits whenever the channel holds two values. A channel keeps its messages in the order they were sent, so rest is in order. When the producer ends, its tx is dropped, and rx.iter() stops.

sync_channel(0) has no room at all. Each send waits until the receiver takes the value. Use it when you want the two threads to meet.

Deadlock: two threads, two locks

Locks bring a new way to fail. Thread A holds lock 1 and waits for lock 2. Thread B holds lock 2 and waits for lock 1. Each is waiting for the other to let go, and neither will. That’s a deadlock. The program doesn’t crash. It just stops, forever.

Rust’s compiler prevents data races, but it can’t prevent deadlocks. They’re a mistake in the order you take locks, not in how memory is shared.

A real deadlock only happens when the timing is unlucky, and then the program hangs. Neither is good for a demonstration. So we’ll force the timing with a Barrier, and we’ll ask for the second lock with try_lock, which reports the problem instead of waiting. A Barrier::new(2) makes each thread wait at barrier.wait() until both threads have arrived:

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

fn take_both(name: &str, first: &Mutex<i32>, second: &Mutex<i32>, barrier: &Barrier) -> String {
    let held = first.lock().unwrap();
    barrier.wait();
    let report = match second.try_lock() {
        Ok(other) => format!("{name}: got lock {} and lock {}", *held, *other),
        Err(_) => format!("{name}: holds lock {}, would wait forever", *held),
    };
    barrier.wait();
    report
}

fn main() {
    let lock1 = Mutex::new(1);
    let lock2 = Mutex::new(2);
    let barrier = Barrier::new(2);

    thread::scope(|s| {
        let a = s.spawn(|| take_both("A", &lock1, &lock2, &barrier));
        let b = s.spawn(|| take_both("B", &lock2, &lock1, &barrier));
        println!("{}", a.join().unwrap());
        println!("{}", b.join().unwrap());
    });
}

It prints:

A: holds lock 1, would wait forever
B: holds lock 2, would wait forever

We ran it 20 times, and it printed exactly this every time, and ended every time. Here’s why it can’t go any other way:

  • Thread A takes lock 1, and thread B takes lock 2. They take them in opposite order, because main passes the locks to B the other way round.
  • The first barrier.wait() holds both threads until both have their first lock.
  • Each tries the other lock. It’s held, so try_lock fails. With lock, this is where both threads would wait forever.
  • The second barrier.wait() keeps both guards alive until both threads have tried. Without it, one thread could finish and release its lock before the other tried, and the other would succeed.

The animation shows the same thing as arrows, and then the fix.

solid arrow: holds the lock dashed red arrow: waiting for it deadlock thread A thread B lock 1 lock 2 both locks are free A holds lock 1, B holds lock 2 A waits for lock 2, B waits for lock 1 each waits for the other: deadlock fix: A holds 1 and 2, B waits for 1 A is done: B takes lock 1, then lock 2 two threads, two locks, one Barrier to line them up A locks 1, B locks 2, then both wait at the barrier A asks for lock 2, B asks for lock 1: neither can go on a cycle: A waits for B, B waits for A, nobody lets go the fix: both take lock 1 first, so B waits and holds nothing A drops both guards, and B gets lock 1 and lock 2 in turn

Two threads taking two locks in opposite orders can each end up waiting for the other. If both take lock 1 first, one of them waits with nothing held, and the cycle can’t form.

Here are those steps in words, in case the animation doesn’t play for you:

  1. Two threads, A and B, and two locks, lock 1 and lock 2. Both locks are free. A Barrier will line the threads up.
  2. A locks lock 1, and B locks lock 2. Then both wait at the barrier. A solid arrow means “holds”.
  3. A asks for lock 2, and B asks for lock 1. A dashed red arrow means “waiting for”. Neither request can be granted.
  4. The arrows form a cycle: A waits for B, and B waits for A. Nobody lets go. That’s the deadlock.
  5. The fix: both threads take lock 1 first. Whichever gets it first, here A, goes on to take lock 2. B waits for lock 1, and it holds nothing while it waits.
  6. A finishes and drops both guards. Now B takes lock 1 and then lock 2, and finishes too.

The fix: take locks in one order

A deadlock needs a cycle of waiting. If every thread takes the locks in the same order, lock 1 before lock 2, there can’t be one. A thread waiting for lock 1 holds nothing, so nobody can be waiting for it. Here’s take_both with both threads taking lock 1 first. There’s no barrier this time, because the threads no longer need to be lined up:

use std::sync::Mutex;
use std::thread;

fn take_both(name: &str, first: &Mutex<i32>, second: &Mutex<i32>) -> String {
    let held = first.lock().unwrap();
    let other = second.lock().unwrap();
    format!("{name}: got lock {} and lock {}", *held, *other)
}

fn main() {
    let lock1 = Mutex::new(1);
    let lock2 = Mutex::new(2);

    thread::scope(|s| {
        let a = s.spawn(|| take_both("A", &lock1, &lock2));
        let b = s.spawn(|| take_both("B", &lock1, &lock2));
        println!("{}", a.join().unwrap());
        println!("{}", b.join().unwrap());
    });
}

It prints:

A: got lock 1 and lock 2
B: got lock 1 and lock 2

This one uses lock, which waits, and it can’t hang. We ran it 20 times to be sure. Either thread may go first, but we print the results in a fixed order after join, so the output is the same each time.

Worked example: reading a guard error

Here’s a mistake almost everyone makes once:

use std::sync::Mutex;

fn main() {
    let counter = Mutex::new(0);
    counter.lock().unwrap() += 1;
    println!("{:?}", counter);
}

It prints:

error[E0368]: binary assignment operation `+=` cannot be applied to type `std::sync::MutexGuard<'_, {integer}>`
...
help: `+=` can be used on `{integer}` if you dereference the left-hand side
  |
5 |     *counter.lock().unwrap() += 1;
  |     +

How to read it:

  1. The left side of += has type MutexGuard<'_, {integer}>. That’s the guard, not the number. {integer} means “some integer type the compiler hasn’t settled on yet”.
  2. A guard isn’t a number, so you can’t add to it. It points to the number, the way a &mut i32 does.
  3. The help: line gives the fix: put * in front to reach the value inside. *counter.lock().unwrap() += 1; takes the lock, adds 1, and releases the lock at the end of the line, because the guard is a temporary.

Worked example: counting words with a channel

Three workers each count the words in their share of the text. Each one sends its counts to main, which adds them up. No worker shares anything, so there’s no lock. Each map is moved through the channel to its new owner:

use std::collections::BTreeMap;
use std::sync::mpsc;
use std::thread;

fn main() {
    let chunks = vec![
        vec!["the cat sat", "the dog ran"],
        vec!["a cat ran", "the end"],
        vec!["dog and cat"],
    ];

    let (tx, rx) = mpsc::channel();
    for lines in chunks {
        let tx = tx.clone();
        thread::spawn(move || {
            let mut counts = BTreeMap::new();
            for line in lines {
                for word in line.split_whitespace() {
                    *counts.entry(word).or_insert(0) += 1;
                }
            }
            tx.send(counts).unwrap();
        });
    }
    drop(tx);

    let mut total = BTreeMap::new();
    let mut reports = 0;
    for counts in rx {
        reports += 1;
        for (word, n) in counts {
            *total.entry(word).or_insert(0) += n;
        }
    }
    println!("{reports} workers reported");
    for (word, n) in &total {
        println!("{word:>4} {n}");
    }
}

It prints:

3 workers reported
   a 1
 and 1
 cat 3
 dog 2
 end 1
 ran 2
 sat 1
 the 3

The reports arrive in a different order on each run, but adding is the same in any order, and a BTreeMap from Part 13 prints its keys sorted. So the output is the same every time. We checked it 20 times.

Notice drop(tx) again. Without it, for counts in rx would wait forever after the third report. This shape, “workers send, one collector receives”, often needs no lock at all.

Worked example: two bank transfers

Two accounts, each a Mutex<i32>. One thread moves money from account 0 to account 1, and the other moves money back. A transfer has to lock both accounts, so that nobody sees the money halfway. Here’s the first version most people write. It builds and passes clippy, and you shouldn’t run it:

use std::sync::Mutex;
use std::thread;

fn transfer(accounts: &[Mutex<i32>; 2], from: usize, to: usize, amount: i32) {
    let mut source = accounts[from].lock().unwrap();
    let mut target = accounts[to].lock().unwrap();
    *source -= amount;
    *target += amount;
}

fn main() {
    let accounts = [Mutex::new(500), Mutex::new(500)];
    thread::scope(|s| {
        s.spawn(|| {
            for _ in 0..100 {
                transfer(&accounts, 0, 1, 3);
            }
        });
        s.spawn(|| {
            for _ in 0..100 {
                transfer(&accounts, 1, 0, 1);
            }
        });
    });
    println!("done");
}

The first thread locks account 0 and then account 1. The second locks account 1 and then account 0. That’s our deadlock, without the barrier to force it. Most runs finish, because one thread gets both locks before the other starts. But sometimes the threads interleave just wrong, and the program stops. We ran it 20 times with a 5-second timeout, and 4 of those runs hung and had to be killed. On your machine the count will differ. That’s what makes deadlocks hard: the program passes a test, then hangs in production.

The fix is a rule: always lock the lower-numbered account first, whichever way the money goes:

use std::sync::Mutex;
use std::thread;

fn transfer(accounts: &[Mutex<i32>; 2], from: usize, to: usize, amount: i32) {
    let (low, high) = (from.min(to), from.max(to));
    let mut first = accounts[low].lock().unwrap();
    let mut second = accounts[high].lock().unwrap();
    if from == low {
        *first -= amount;
        *second += amount;
    } else {
        *second -= amount;
        *first += amount;
    }
}

fn main() {
    let accounts = [Mutex::new(500), Mutex::new(500)];

    thread::scope(|s| {
        s.spawn(|| {
            for _ in 0..100 {
                transfer(&accounts, 0, 1, 3);
            }
        });
        s.spawn(|| {
            for _ in 0..100 {
                transfer(&accounts, 1, 0, 1);
            }
        });
    });

    let a = *accounts[0].lock().unwrap();
    let b = *accounts[1].lock().unwrap();
    println!("account 0: {a}, account 1: {b}, total: {}", a + b);
}

It prints:

account 0: 300, account 1: 700, total: 1000

We ran this one 20 times, and it finished every time with the same numbers. Account 0 lost 100 × 3 and gained 100 × 1. The total is still 1000, because each transfer holds both locks while it moves the money. Nobody ever sees it in neither account, or in both.

The same rule works for any number of locks: give them an order, such as an index or an id, and always take them in that order.

Tips and traps

  • Changing data inside an Arc (E0594 or E0596). “cannot assign to data in an Arc” or “cannot borrow data in an Arc as mutable”. An Arc only gives shared access. Put a Mutex, an RwLock or an atomic inside it.
  • Holding a guard too long. A guard declared at the top of a function holds the lock until the function ends, and every other thread waits. Put the locked work in its own block, or call drop(guard) as soon as you’re done.
  • Locking the same mutex twice in one thread. The second lock never returns. The docs say it may deadlock or panic, and they don’t promise which. It often happens when a function holding a guard calls a helper that locks the same mutex. Pass the guarded value to the helper instead of the mutex.
  • A receiver loop that never ends. for msg in rx finishes all the work, then hangs. Some Sender is still alive, usually the original tx in main. Call drop(tx) after the last clone.
  • Taking two locks in different orders. The program usually works and sometimes hangs. Pick one order for every lock, and take them in that order everywhere.
  • Reaching for Ordering::SeqCst or Acquire without knowing why. For a counter, Relaxed is correct. If an atomic is meant to protect other data, use a Mutex instead, until you’ve read the docs on orderings.
  • Sharing when you could send. If each thread can work on its own data and send back a result, do that. A channel, or the return value of join, is easier to get right than a lock.

A lock is released when its guard is dropped, so keep guards short, and take locks in the same order everywhere.

Exercises

Exercise 1. This program prints nothing and never ends. Find the reason, and fix it with one line so it prints [10, 20, 30].

use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();
    for id in 1..=3 {
        let tx = tx.clone();
        thread::spawn(move || tx.send(id * 10).unwrap());
    }

    let mut got: Vec<i32> = rx.iter().collect();
    got.sort();
    println!("{got:?}");
}

Exercise 2. This program counts the multiples of 7 up to 3000 on three threads, with a Mutex. Change it to use an AtomicUsize instead, so there’s no lock at all.

use std::sync::Mutex;
use std::thread;

fn main() {
    let found = Mutex::new(0);
    thread::scope(|s| {
        for start in [1, 1001, 2001] {
            let found = &found;
            s.spawn(move || {
                for n in start..start + 1000 {
                    if n % 7 == 0 {
                        *found.lock().unwrap() += 1;
                    }
                }
            });
        }
    });
    println!("multiples of 7 up to 3000: {}", found.lock().unwrap());
}

It prints:

multiples of 7 up to 3000: 428

Exercise 3. log_size uses try_lock, so it reports busy instead of hanging. Why does it say busy, and how do you make it print size: 2 without changing log_size?

use std::sync::Mutex;

fn log_size(list: &Mutex<Vec<i32>>) {
    match list.try_lock() {
        Ok(v) => println!("size: {}", v.len()),
        Err(_) => println!("size: busy"),
    }
}

fn main() {
    let list = Mutex::new(Vec::new());
    let mut guard = list.lock().unwrap();
    guard.push(1);
    guard.push(2);
    log_size(&list);
}

It prints:

size: busy
Answers

1. main still owns the original tx. The three threads drop their clones when they end, but the channel stays open while any Sender is alive, so rx.iter() waits forever. Add drop(tx); after the loop that clones it:

use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();
    for id in 1..=3 {
        let tx = tx.clone();
        thread::spawn(move || tx.send(id * 10).unwrap());
    }
    drop(tx);

    let mut got: Vec<i32> = rx.iter().collect();
    got.sort();
    println!("{got:?}");
}

It prints:

[10, 20, 30]

The sort matters: the three threads may send in any order. We ran it 20 times, and it printed the same line every time.

2. fetch_add takes &self, so each thread can share a plain &AtomicUsize. Relaxed is enough, because the count is the only thing the threads share, and the scope waits for all three before we read it.

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

fn main() {
    let found = AtomicUsize::new(0);
    thread::scope(|s| {
        for start in [1, 1001, 2001] {
            let found = &found;
            s.spawn(move || {
                for n in start..start + 1000 {
                    if n % 7 == 0 {
                        found.fetch_add(1, Ordering::Relaxed);
                    }
                }
            });
        }
    });
    println!(
        "multiples of 7 up to 3000: {}",
        found.load(Ordering::Relaxed)
    );
}

It prints:

multiples of 7 up to 3000: 428

3. guard is still alive when main calls log_size, so main itself holds the lock. With lock instead of try_lock, this program would deadlock or panic (the docs don’t say which): the thread would ask for a lock it already holds. Put the pushes in a block, so the guard is dropped before the call:

use std::sync::Mutex;

fn log_size(list: &Mutex<Vec<i32>>) {
    match list.try_lock() {
        Ok(v) => println!("size: {}", v.len()),
        Err(_) => println!("size: busy"),
    }
}

fn main() {
    let list = Mutex::new(Vec::new());
    {
        let mut guard = list.lock().unwrap();
        guard.push(1);
        guard.push(2);
    }
    log_size(&list);
}

It prints:

size: 2

drop(guard); before the call works too.

What’s next

Threads made with thread::spawn need everything they capture to be 'static, and that word has come up a few times without a full explanation. In Part 25, we go back to lifetimes: what 'static really means, what T: 'a says, and how to read the borrow checker’s hardest errors.

How useful was this post?

Click on a heart to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.