Threads and move
What you'll learn:
- start a thread with
thread::spawnand wait for it withjoin; - 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 whyRccannot do it.

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:
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:
use std::thread;makes the name of thethreadmodule from the standard library available.thread::spawntakes 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 typeJoinHandle. We put it inh.- While the thread computes,
mainprintsmain works. h.join()waits until the thread finishes and returns aResultholding the value the closure returned.unwraptakes55out of it.- 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:
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:
main 1
main 2
main 3
thread 1
thread 2
thread 3On 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.
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:
vhas moved into the thread, andmaincan no longer use it: the compiler answers with error E0382;- a
Copyvalue, such as ani32, is copied, and the original variable stays inmain; - if both the thread and
mainneed the vector, writelet 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:
use std::thread;
fn main() {
let v = vec![1, 2, 3];
let h = thread::spawn(|| v.len()); // ✗
println!("{}", h.join().unwrap());
}error[E0373]: closure may outlive the current function, but it borrows `v`, which is owned by the current functionThe 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::spawnruns a closure in a new thread and immediately returns aJoinHandle;joinwaits 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
mainends. - Without
movethe closure borrows variables, andspawnrefuses with error E0373 — even whenjoinis on the next line. movemoves what was captured into the thread: aVecleavesmain, and aCopyvalue is copied.