Skip to content
Theory · Threads · lesson 1 of 7

Threads and move

What you'll learn

What you'll learn:

  • start a thread with thread::spawn and wait for it with join;
  • explain why a thread's closure needs move;
  • pass values from one thread to another through a channel;
  • share one value between threads with Arc<Mutex<T>> and explain why Rc cannot do it.
Work goes on at once at three benches, the middle one main and two side ones spawn, and a finished crate rides along join to the middle

Picture a workshop. Until now one craftsman worked in it: he took a recipe and followed it line by line. While he saws a board, everything else waits.

Now let's hire more workers. Each one stands at a bench and does a part of the order, and they all work at the same time. Such a worker in a program is called a thread. Every program has at least one thread — the main one, where main runs.

Why do you need threads? While one computes, another reads a file and a third answers the user. A computer with several cores really does run them at the same moment.

Starting a thread

Let's hire a worker to add up the numbers from 1 to 10 while we print a line ourselves:

Rust
use std::thread;

fn main() {
    let h = thread::spawn(|| {
        let mut sum = 0;
        for i in 1..=10 {
            sum += i;
        }
        sum
    });
    println!("main works"); // main works
    let sum = h.join().unwrap();
    println!("sum = {sum}"); // sum = 55
}

Let's go through the example line by line:

  1. use std::thread; makes the name of the thread module from the standard library available.
  2. thread::spawn takes a closure and runs it in a new thread. The call does not wait for the work to finish; it immediately returns the thread's handle, a value of type JoinHandle. We put it in h.
  3. While the thread computes, main prints main works.
  4. h.join() waits until the thread finishes and returns a Result holding the value the closure returned. unwrap takes 55 out of it.
  5. The last line prints sum = 55.

join returns a Result because the thread may panic. The panic then stops only that thread, and join returns Err.

There is a second reason to call join. When main ends, the whole program exits, and every thread that has not finished its work is cut off mid-sentence.

The order is not guaranteed

Here the workshop picture stops being accurate. Real workers agree on who goes first. Threads do not: the operating system decides when each of them runs. Let both of them print:

Rust
use std::thread;

fn main() {
    let h = thread::spawn(|| {
        for i in 1..=3 {
            println!("thread {i}");
        }
    });
    for i in 1..=3 {
        println!("main {i}");
    }
    h.join().unwrap();
}

One run printed this:

TEXT
main 1
main 2
main 3
thread 1
thread 2
thread 3

On another run the thread's lines may come first or mix with the lines of main. That is why in this theme's examples only one thread prints, or the printing comes after join.

A thread needs move

You remember from the theme on closures: a closure takes a variable in the weakest way that is enough for it. If the body only reads a vector, the closure borrows it.

That does not work for a thread. A thread may run longer than the function that started it: main is allowed to end first. A reference in the thread would then point at destroyed data. That is why thread::spawn accepts only a closure that holds no references to local variables.

The way out is move: the closure takes the whole vector, and the thread becomes its owner.

Rust
use std::thread;

fn main() {
    let v = vec![1, 2, 3];
    let h = thread::spawn(move || v.len());
    println!("{}", h.join().unwrap()); // 3
}

What to know about move in a thread:

  • v has moved into the thread, and main can no longer use it: the compiler answers with error E0382;
  • a Copy value, such as an i32, is copied, and the original variable stays in main;
  • if both the thread and main need the vector, write let v2 = v.clone(); and move the copy into the thread.

"Why does thread::spawn need move?" is a common interview question.

Common mistake

move is left out, since join sits on the next line and main will wait for the thread anyway:

Rust
use std::thread;

fn main() {
    let v = vec![1, 2, 3];
    let h = thread::spawn(|| v.len()); // ✗
    println!("{}", h.join().unwrap());
}
TEXT
error[E0373]: closure may outlive the current function, but it borrows `v`, which is owned by the current function

The program does not compile, and nothing runs. The compiler checks only the signature of spawn, not what the program does with the thread later, so the join below changes nothing. In its help, rustc itself suggests adding move before the closure.

Key points

  • thread::spawn runs a closure in a new thread and immediately returns a JoinHandle; join waits for the thread to end and hands over its result.
  • The operating system picks the order in which threads run, and unfinished threads are cut off when main ends.
  • Without move the closure borrows variables, and spawn refuses with error E0373 — even when join is on the next line.
  • move moves what was captured into the thread: a Vec leaves main, and a Copy value is copied.