CourseLesson 14 · ConcurrencySolve

Lesson 14

Concurrency

Every program you have written so far runs one line at a time, from the top of main to the bottom. Concurrency means running more than one part of a program at the same time. This lesson covers the three ways Rust lets you do that safely: starting a separate thread, sending values between threads instead of sharing them, and sharing a value behind a lock when it really has to be shared.

Threads and std::thread

A thread is a separate line of a program running at the same time as the rest of it. A program starts with one thread, running main. Calling thread::spawn starts a second thread, which runs the closure passed to it while the first thread keeps going.

use std::thread;

fn main() {
    let handle = thread::spawn(|| {
        let mut total = 0;
        for n in 1..=5 {
            total += n;
        }
        total
    });

    let result = handle.join().unwrap();
    println!("{result}");
}
15
  • thread::spawn takes a closure and runs it on a new thread. It returns a JoinHandle right away, without waiting for the thread to finish.

  • handle.join() blocks the current thread until the spawned thread finishes, then returns whatever the closure returned, wrapped in a Result. .unwrap() is needed for the same reason it is needed after opening a file: the call can fail, here only if the thread panicked.

  • Without join, there is no way to get total back out of the thread that computed it.

Capturing Data with move

A closure passed to thread::spawn usually needs to use a variable from the surrounding code. Because the new thread might still be running after the function that started it has returned, the closure is not allowed to borrow that variable. It has to own it.

use std::thread;

fn main() {
    let name = String::from("Ada");

    let handle = thread::spawn(move || {
        println!("hello from the thread, {name}");
    });

    handle.join().unwrap();
}
hello from the thread, Ada

move makes the closure take ownership of name instead of borrowing it. Once moved, name can no longer be used in main. Leave move out, and the compiler refuses to build the program.

use std::thread;

fn main() {
    let name = String::from("Ada");

    let handle = thread::spawn(|| {
        println!("hello from the thread, {name}");
    });

    handle.join().unwrap();
}
error[E0373]: closure may outlive the current function, but
              it borrows `name`, which is owned by the
              current function
 --> src/main.rs:6:32
  |
6 |     let handle = thread::spawn(|| {
  |                                ^^ may outlive borrowed
  |                                   value `name`
7 |         println!("hello from the thread, {name}");
  |                                           ---- `name` is
  |                                           borrowed here
  |
help: to force the closure to take ownership of `name`, use
      the `move` keyword
  |
6 |     let handle = thread::spawn(move || {

Key idea

Almost every closure passed to thread::spawn needs move in front of it. Read the compiler’s suggestion literally: add move, and the closure owns what it needs instead of borrowing something that might not still exist by the time the thread runs.

Threads Run Independently

The spawned thread and the thread that spawned it are not kept in step with each other, unless something makes one of them wait. If main never calls join, it keeps running without waiting for the spawned thread at all.

use std::thread;

fn main() {
    thread::spawn(|| {
        println!("from the spawned thread");
    });

    println!("from main");
}

This program does not have one fixed output. Most of the time main finishes printing first, because starting a thread takes longer than printing one line. Sometimes the two lines print in the other order. Sometimes the program ends before the spawned thread gets to run at all, and only from main appears. A program ends the moment main returns, and every thread still running at that point is stopped without finishing.

Key idea

Call join whenever the rest of the program needs a spawned thread to have finished, whether that is to read a value it computed or simply to be sure its work happened. Without join, a spawned thread is a promise that might not be kept.

Sharing State with Arc<T> and Mutex<T>

Sometimes several threads genuinely need to change the same value, such as a running total that every thread adds to. Arc<T>, short for atomic reference counted, allows more than one thread to own the same value, the way Rc<T> allows more than one variable to own a value on a single thread. Mutex<T>, short for mutual exclusion, guards the value so that only one thread at a time can change it.

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

fn main() {
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];

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

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

    println!("counter: {}", counter.lock().unwrap());
}
counter: 10
  • Arc::clone(&counter) gives each thread its own owner of the same Mutex, the same way Rc::clone works for a single thread. The count of owners is changed with an operation that cannot be interrupted partway through by another thread, which is why Arc is safe here and Rc is not.

  • counter.lock() waits until no other thread is holding the value, then returns it, wrapped in a Result the same way join is. It unlocks again automatically once value goes out of scope.

  • Ten threads all try to add one to counter, but the lock forces them to do it one at a time. Without the lock, two threads could both read the same starting number, both add one, and both write back the same result, losing an update.

  • Every handle is collected into handles and joined before the final println!, so all ten additions are guaranteed to have happened by the time the count is read.

Message Passing with Channels

A channel sends values from one thread to another instead of letting them share one variable. One end sends, the other end receives, and the value belongs to whichever end currently holds it, never to both.

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

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

    thread::spawn(move || {
        let words = vec!["one", "two", "three"];
        for word in words {
            tx.send(word).unwrap();
        }
    });

    for received in rx {
        println!("got: {received}");
    }
}
got: one
got: two
got: three
  • mpsc::channel() returns two halves: tx, the sender (short for transmitter), and rx, the receiver. mpsc stands for multiple producer, single consumer: a channel can have many senders, but only one receiver.

  • tx.send(word) moves word into the channel. Once sent, the spawned thread no longer owns it.

  • for received in rx reads one value at a time as it arrives, in the order it was sent, and keeps going until every sender is gone.

  • move is needed here for the same reason it was needed with thread::spawn earlier: the closure has to own tx instead of borrowing it.

A channel with only one sender left, and nothing more to send, closes itself.

use std::sync::mpsc;

fn main() {
    let (tx, rx) = mpsc::channel::<i32>();
    drop(tx);

    match rx.recv() {
        Ok(value) => println!("got: {value}"),
        Err(_) => println!("the channel is closed"),
    }
}
the channel is closed

rx.recv() waits for one value and returns it wrapped in a Result, the same way the for loop above reads values one at a time behind the scenes. Dropping tx removes the only sender, so there is no way a value could ever arrive. recv returns Err straight away instead of waiting forever.

Cloning the sender lets more than one thread send into the same channel.

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

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

    let mut handles = vec![];
    for id in 0..3 {
        let tx = tx.clone();
        handles.push(thread::spawn(move || {
            tx.send(id * 10).unwrap();
        }));
    }
    drop(tx);

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

    let mut received: Vec<i32> = rx.iter().collect();
    received.sort();
    println!("{received:?}");
}
[0, 10, 20]
  • Each of the three threads gets its own clone of tx and sends one value.

  • drop(tx) removes the original sender. Without this line, the channel would still have a live sender, the original tx, even after all three threads finish, so rx.iter() would keep waiting for a value that never comes.

  • Three threads sending at nearly the same moment can arrive in any order, so the values are collected into a Vec and sorted before printing, rather than printed as they arrive.

The Send and Sync Traits

Send and Sync are traits with no methods. A type either has them or it does not, and the compiler decides that for you, not you. Send means a value of that type is safe to move to a different thread. Sync means a reference to that type, &T, is safe to share between threads at the same time. Almost every type has both. Rc<T> and RefCell<T> are the two you have already met that do not.

use std::rc::Rc;
use std::thread;

fn main() {
    let name = Rc::new(String::from("Ada"));

    let handle = thread::spawn(move || {
        println!("{name}");
    });

    handle.join().unwrap();
}
error[E0277]: `Rc<String>` cannot be sent between threads
              safely
 --> src/main.rs:7:32
  |
7 |     let handle = thread::spawn(move || {
  |                                ^^^^^^^
  |   `Rc<String>` cannot be sent between threads safely
  |
  = help: the trait `Send` is not implemented for
    `Rc<String>`

Rc’s count of owners is a plain number, changed with no protection against two threads changing it at the same instant. Moving an Rc to another thread would make that possible, so Rc<T> is not Send, and the compiler refuses the program before it ever runs. Arc<T> exists because of this: it works the same way as Rc<T>, but its count is Send and Sync.

RefCell<T> is not Sync, because its borrow count is also a plain number, checked and changed with no protection against two threads doing it at once.

use std::cell::RefCell;
use std::sync::Arc;
use std::thread;

fn main() {
    let shared = Arc::new(RefCell::new(0));
    let shared2 = Arc::clone(&shared);

    let handle = thread::spawn(move || {
        *shared2.borrow_mut() += 1;
    });

    handle.join().unwrap();
    println!("{}", shared.borrow());
}
error[E0277]: `RefCell<i32>` cannot be shared between
              threads safely
 --> src/main.rs:9:32
  |
9 |     let handle = thread::spawn(move || {
  |                                ^^^^^^^
  |   `RefCell<i32>` cannot be shared between threads safely
  |
  = help: the trait `Sync` is not implemented for
    `RefCell<i32>`
  = note: required for `Arc<RefCell<i32>>` to implement
    `Send`

Wrapping RefCell<i32> in Arc does not help. Arc<T> is only Send when T is both Send and Sync, because sharing an Arc across threads means every thread can reach the value inside it at once. Mutex<T> is the fix: it is Sync even when T is not, because its lock guarantees only one thread reaches the value at a time.

Key idea

Send and Sync turn a whole class of threading mistakes into a compile error instead of a bug that only shows up when two threads happen to collide at the wrong moment. When the compiler refuses a type across threads, reach for Arc in place of Rc, and Mutex in place of RefCell, rather than looking for a way around the error.

Common Mistakes

Forgetting to Join a Thread

A spawned thread that is never joined might finish before main returns, or it might not. Nothing about the program guarantees either outcome. If the rest of the program depends on that thread’s work being done, whether that is reading a value it produced or simply relying on a side effect like a printed line, join it first.

Locking a Mutex Twice on the Same Thread

use std::sync::Mutex;

fn main() {
    let m = Mutex::new(5);

    let first = m.lock().unwrap();

    match m.try_lock() {
        Ok(_) => println!("got the lock"),
        Err(_) => println!("already locked"),
    }

    println!("{first}");
}
already locked
5

try_lock returns straight away with an Err if the lock is already held, instead of waiting. Plain lock does not have that choice: a second, ordinary m.lock() call on the same thread while first is still alive would wait forever for a lock that thread itself is holding and will never release. A RefCell panics the moment a borrowing rule is broken. A Mutex locked twice on one thread deadlocks instead: the program does not crash, it simply stops making progress.

Sending After the Receiver Is Dropped

use std::sync::mpsc;

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

    match tx.send(1) {
        Ok(()) => println!("sent"),
        Err(_) => println!("nobody is listening"),
    }
}
nobody is listening

send does not block waiting for a receiver, and it does not panic when there is none left. It returns Err, and the value passed to send is dropped instead of delivered. Always check the result of send in a program where the receiving thread might have already stopped.

Reaching for Rc or RefCell Out of Habit

Rc<T> and RefCell<T> are the right choice inside a single thread, but the compiler refuses both the moment a thread is involved. Seeing either error is a sign to switch to the thread-safe version, Arc<T> for Rc<T> and Mutex<T> for RefCell<T>, not a sign that something else is wrong with the program.

Reference

Written asWhat it does
thread::spawn(f)Runs f on a new thread and returns a handle to it.
handle.join()Waits for that thread to finish, returns what f returned.
move !||! …A closure that takes ownership of the variables it uses.
Arc<T>A value with more than one owner, safe across threads.
Arc::clone(&a)A cheap new owner, count up by one.
Mutex<T>A value only one thread can access at a time.
m.lock()Waits, then returns exclusive access to m’s value.
m.try_lock()Returns Err at once if m is already locked.
mpsc::channel()Returns a connected sender and receiver.
tx.send(v)Moves v into the channel. Err if no receiver is left.
rx.recv()Waits for one value. Err once every sender is gone.
for v in rxReads values as they arrive until every sender is gone.
tx.clone()A second sender for the same channel.
SendSafe to move a value of this type to another thread.
SyncSafe to share &T of this type between threads.

Check what stuck

The practice sheet for this lesson has 45 multiple-choice questions. Each one is a short program: pick what it prints, or why it does not compile.

Start practice →