A thread runs code side by side with the rest of your program. This part shows thread::spawn and join, why spawn needs move, how scoped threads borrow safely, and what Send and Sync mean.
A thread is a second line of work inside the same program. Rust lets you start one with a single function call. The hard part is the data: which values may a new thread use, and for how long? Rust answers that question when the program compiles, not when it crashes.
This part covers thread::spawn and join, getting a value back from a thread, why spawn needs a move closure, scoped threads that can borrow, what happens when a thread panics, and the two traits behind all of it, Send and Sync. It builds on closures and move from Part 16 and on Rc from Part 20. Every program here was run on Rust 1.95, and its output is pasted from the run.
Try this first
This program starts a second thread, and the thread prints a name. Will it compile?
use std::thread;
fn main() {
let name = String::from("Ana");
let handle = thread::spawn(|| {
println!("hello from the thread, {name}");
});
handle.join().unwrap();
}
It doesn’t:
error[E0373]: closure may outlive the current function, but it borrows `name`, which is owned by the current function
--> src/main.rs:5:32
|
5 | let handle = thread::spawn(|| {
| ^^ may outlive borrowed value `name`
6 | println!("hello from the thread, {name}");
| ---- `name` is borrowed here
|
note: function requires argument type to outlive `'static`
...
help: to force the closure to take ownership of `name` (and any other referenced variables), use the `move` keyword
|
5 | let handle = thread::spawn(move || {
| ++++
We join the thread on the next line, so name is clearly still alive while the thread runs. The compiler refuses anyway. To see why, we first need to see what spawn does.
A thread runs beside main
Every Rust program starts with one thread, the main thread, which runs main. std::thread::spawn starts another one. You give it a closure, and the new thread runs that closure while the main thread carries on with the next line.
use std::thread;
fn main() {
let handle = thread::spawn(|| {
println!("thread: hello");
});
handle.join().unwrap();
println!("main: the thread has finished");
}
It prints:
thread: hello
main: the thread has finished
spawn returns a JoinHandle. Calling join on it makes the main thread wait until the new thread has finished. That’s why the two lines always come in this order. Without the join, the main thread could reach its println! first, or the other thread could. The operating system decides which thread runs when, and the order can change from one run to the next.
join returns a Result. It’s Ok when the thread finished normally, and Err when it panicked. We’ll look at the Err case below. For now, unwrap is enough.
When main ends, the program ends
A spawned thread doesn’t keep the program alive. When main returns, the whole process exits, and any thread still running is stopped where it is. It doesn’t get to finish, and the values it owns aren’t dropped.
This thread waits forever. thread::park puts a thread to sleep until another thread wakes it up, and nothing here ever does:
use std::thread;
fn main() {
thread::spawn(|| {
loop {
thread::park();
}
});
println!("main: done, and not waiting");
}
It prints:
main: done, and not waiting
The program still ends at once. We dropped the JoinHandle without calling join, which detaches the thread: nobody waits for it. If we had joined this one, main would wait forever too.
The same thing happens to a thread that’s just slow. If its work isn’t done when main returns, the work is lost, and any line it hadn’t printed yet never appears. So the rule is simple: join every thread whose work you need.
Getting a value back
The closure you pass to spawn can return a value. join hands it back, inside the Ok:
use std::thread;
fn main() {
let handle = thread::spawn(|| {
let mut total = 0;
for n in 1..=100 {
total += n;
}
total
});
let total = handle.join().unwrap();
println!("1 + 2 + ... + 100 = {total}");
}
It prints:
1 + 2 + ... + 100 = 5050
The handle has a type: JoinHandle<i32> here, because the closure returns an i32. With several threads, keep the handles in a Vec and join them in order:
use std::thread;
fn main() {
let mut handles = Vec::new();
for i in 1..=4 {
let handle = thread::spawn(move || i * i);
handles.push(handle);
}
for handle in handles {
let square = handle.join().unwrap();
println!("got {square}");
}
}
It prints:
got 1
got 4
got 9
got 16
The four threads may finish in any order. The output can’t change, though, because only main prints, and it joins the handles in the order it made them. This is the pattern to reach for: threads compute, main collects. Notice the move in move || i * i. That’s our next topic.
Why spawn needs move
Here is the signature of spawn, from the standard library:
pub fn spawn<F, T>(f: F) -> JoinHandle<T>
where
F: FnOnce() -> T,
F: Send + 'static,
T: Send + 'static,
Two bounds on the closure F matter. Send comes later in this part. 'static means “this closure holds no borrows that could run out”. Part 9 introduced 'static; Part 25 goes deeper. For now, read F: 'static as “the closure owns everything it uses, or only borrows things that live for the whole program”.
Now look at the Try-this-first program again. The closure only reads name, so it captures &name, a borrow (Part 16 showed how the compiler picks). A borrow of a local variable isn’t 'static, because name is dropped when main returns.
“But we join before main returns.” True, and the compiler doesn’t look that far. spawn has no way to know the handle will be joined. You could drop the handle, as we did above, and then the thread would still be reading name after main had freed it. The signature has to be safe for every caller, so it asks for 'static, and the error says the closure “may outlive the current function”. Note the word may.
The help: line gives the fix. With move, the closure owns name, and it carries the string to the new thread:
use std::thread;
fn main() {
let name = String::from("Ana");
let handle = thread::spawn(move || {
println!("hello from the thread, {name}");
});
handle.join().unwrap();
}
It prints:
hello from the thread, Ana
After the move, main can’t use name any more. A println! of name after the spawn fails with E0382, “borrow of moved value”, the error from Part 6.
If both threads need the string, give the thread its own copy. Clone before the closure, and move the clone in:
use std::thread;
fn main() {
let name = String::from("Ana");
let for_thread = name.clone();
let handle = thread::spawn(move || {
println!("hello from the thread, {for_thread}");
});
handle.join().unwrap();
println!("back in main, {name}");
}
It prints:
hello from the thread, Ana
back in main, Ana
Cloning is fine for a name. For a big vector that each thread only needs to read, copying it once per thread is a waste. That’s where scoped threads come in.
Scoped threads can borrow
std::thread::scope gives you a scope, a region of code that all its threads must finish inside. You call scope with a closure. It hands that closure a value s, and s.spawn starts a thread that belongs to the scope. When the closure ends, scope joins every thread that’s still running before it returns.
That one promise changes everything. The threads can’t outlive the scope, and the scope can’t outlive main‘s local variables. So the threads may borrow them, with no move and no clone:
use std::thread;
fn main() {
let numbers = vec![1, 2, 3, 4, 5, 6];
let name = String::from("Ana");
thread::scope(|s| {
s.spawn(|| {
let sum: i32 = numbers.iter().sum();
println!("sum is {sum}");
});
s.spawn(|| {
println!("{name} has {} numbers", numbers.len());
});
});
println!("after the scope: {numbers:?}, {name}");
}
It prints (the first two lines can come in either order):
sum is 21
Ana has 6 numbers
after the scope: [1, 2, 3, 4, 5, 6], Ana
Both threads read numbers at the same time. That’s allowed, for the same reason two & borrows are allowed in Part 7: many readers are safe. After the scope, main uses both variables again. Nothing was moved.
The borrow rules don’t relax. A scoped thread may also borrow with &mut, but only one at a time for any piece of data. chunks_mut(2) splits a vector into separate &mut slices of two items each, so each thread can change its own slice:
use std::thread;
fn main() {
let mut scores = vec![10, 20, 30, 40, 50, 60];
thread::scope(|s| {
for chunk in scores.chunks_mut(2) {
s.spawn(|| {
for score in chunk {
*score *= 2;
}
});
}
});
println!("{scores:?}");
}
It prints:
[20, 40, 60, 80, 100, 120]
Three threads changed one vector at once, and the compiler could prove they never touched the same item. thread::scope has been in the standard library since Rust 1.63. Before it, the only safe ways to share a local with a thread were to clone it or to wrap it in Arc. Today, when the threads should finish before the function goes on, a scope is usually the simplest answer.
Send and Sync
The other bound on spawn was Send. Here’s a type that fails it. Rc from Part 20 keeps a count of its owners:
use std::rc::Rc;
use std::thread;
fn main() {
let shared = Rc::new(5);
let handle = thread::spawn(move || {
println!("{shared}");
});
handle.join().unwrap();
}
It prints:
error[E0277]: `Rc<i32>` cannot be sent between threads safely
...
= help: within `{closure@src/main.rs:6:32: 6:39}`, the trait `Send` is not implemented for `Rc<i32>`
note: required because it's used within this closure
...
note: required by a bound in `spawn`
...
128 | F: Send + 'static,
| ^^^^ required by this bound in `spawn`
Read it from the bottom. spawn requires F: Send. The closure owns shared, an Rc<i32>. Rc<i32> isn’t Send, so neither is the closure.
Why not? Every Rc::clone adds 1 to the count, and every drop subtracts 1. Those are plain additions, made with no protection. If two threads changed the same count at the same moment, one change could be lost. The count would be wrong, and the value could be freed while someone still points at it. So the type says no, and the compiler enforces it.
The thread-safe version is Arc, an “atomically reference counted” pointer. It updates its count with special CPU instructions that two threads can’t interfere with. Part 24 covers it with Mutex; here’s a first look:
use std::sync::Arc;
use std::thread;
fn main() {
let shared = Arc::new(String::from("settings"));
let for_thread = Arc::clone(&shared);
let handle = thread::spawn(move || {
println!("thread reads {for_thread}");
});
handle.join().unwrap();
println!("main reads {shared}, count {}", Arc::strong_count(&shared));
}
It prints:
thread reads settings
main reads settings, count 1
The count is back to 1 because the thread’s clone was dropped when the thread finished.
So there are two traits, and they ask two different questions:
Send: may a value of this type be moved to another thread?String,Vec<i32>,Arc<String>and almost everything else: yes.Rc<T>: no.Sync: may several threads hold a&Tto it at the same time?i32,StringandVec<i32>: yes.RefCell<T>andCell<T>: no, because they let you change the value through a shared&(Part 20), with no protection against two threads doing it at once. In fact,TisSyncexactly when&TisSend.
Scoped threads hit Sync, because they share & borrows. Try to change a RefCell from one:
use std::cell::RefCell;
use std::thread;
fn main() {
let counter = RefCell::new(0);
thread::scope(|s| {
s.spawn(|| {
*counter.borrow_mut() += 1;
});
});
println!("{}", counter.borrow());
}
It prints:
error[E0277]: `RefCell<i32>` cannot be shared between threads safely
...
= help: the trait `Sync` is not implemented for `RefCell<i32>`
= note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead
= note: required for `&RefCell<i32>` to implement `Send`
The last note joins the two traits together. The closure holds &RefCell<i32>. To be sent to the thread, that & must be Send, and that needs RefCell<i32> to be Sync. It isn’t.
You never write impl Send for your own types. Send and Sync are auto traits: the compiler implements them for a struct or enum when every field has them. A struct with a String and a u32 is Send and Sync without a word from you. Add one Rc field, and the whole struct stops being Send. That’s why these errors often name a type you didn’t write. The compiler found the Rc several fields down.
Here is the whole picture: what may cross from one thread to another, and how a scope changes the answer for borrows.
Top: a spawned thread takes owned values that are Send. An Rc is stopped by E0277 and a borrow of a local by E0373. Bottom: inside thread::scope, threads may borrow main’s data, because the scope ends before data does.
The figure in words:
- With
thread::spawn, owned values cross the boundary: aString, aVec<i32>, or anArc<T>clone. Each is moved into the closure, and the new thread owns it. - An
Rc<T>is stopped with E0277, becauseRcisn’tSend. - A borrow of a local is stopped with E0373, because the thread might still run after the function returns.
- With
thread::scope, threads may hold&data. The scope joins them all beforemaingoes on, so the borrow always ends beforedatais dropped.
Explain it like I’m ten
You’re cleaning your house, and two friends offer to help.
With spawn, a friend takes a job home. They pack a bag with everything they need, and the bag is theirs now. They can’t use your pencils by pointing at them from their house, because you might throw the pencils away before they’re done. And some things aren’t allowed in the bag at all: the class sign-up sheet that everybody writes on can’t go home with one kid, or two kids will scribble on it at once and the count gets messed up.
With scope, the friends work in your house. They can use your pencils, because you stand at the door and don’t leave until every friend has finished. Two friends can read the same book. Only one at a time can write in it.
The precise version
thread::spawn asks the operating system for a new thread and runs the closure on it. The closure must be Send, so it can move to that thread, and 'static, so it holds no borrow that might end while the thread runs. The compiler can’t follow a JoinHandle to see whether you join it, so it assumes the thread may run forever.
thread::scope relaxes 'static to the scope’s own lifetime. Its signature ties every scoped thread to a lifetime that ends before scope returns, and scope joins all its threads before returning, even when the closure panics. So borrows of locals declared outside the scope are fine. The ordinary borrow rules still apply between threads.
Send and Sync are auto traits that the compiler implements by looking at fields. T: Sync is defined as &T: Send. A few standard types opt out: Rc is neither, Cell and RefCell are Send but not Sync, and raw pointers are neither.
Where the analogy breaks: your friends would notice the messed-up sheet and argue. Threads don’t notice anything. Two threads that change the same memory at once, called a data race, just get wrong results, or worse. Rust doesn’t detect races while the program runs. It rules them out at compile time, with Send, Sync and the borrow rules, so safe Rust code can’t have one at all.
When a thread panics
A panic in a spawned thread stops that thread, not the program. The panic shows up in join, as Err:
use std::thread;
fn main() {
let inputs = ["42", "forty", "7"];
let mut handles = Vec::new();
for text in inputs {
let handle = thread::spawn(move || {
let n: i32 = text.parse().unwrap();
n * 2
});
handles.push(handle);
}
for (text, handle) in inputs.iter().zip(handles) {
match handle.join() {
Ok(doubled) => println!("{text:>6} -> {doubled}"),
Err(_) => println!("{text:>6} -> the thread panicked"),
}
}
println!("main is still running");
}
It prints:
42 -> 84
forty -> the thread panicked
7 -> 14
main is still running
The usual panic message also appears, on standard error, from the thread that panicked. It starts thread '<unnamed>' and an id that changes every run, then continues:
panicked at src/main.rs:8:39:
called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }
<unnamed> is there because we didn’t give the thread a name. The Err holds the panic’s message as a Box<dyn Any + Send>, the Any trait object from Part 21; downcast_ref::<String>() or downcast_ref::<&str>() gets the text out. Most code only needs to know that the thread failed.
If you unwrap the result of join, the panic carries over to the thread that joined. That’s often what you want: a worker’s bug shouldn’t go unnoticed. Scoped threads work the same way, with one difference: if a scoped thread panicked and you never joined it yourself, scope panics when it returns, with the message “a scoped thread panicked”.
Names and the current thread
thread::current() returns a handle to the thread that’s running, and .name() gives its name, if it has one. To name a thread, build it with thread::Builder:
use std::thread;
fn main() {
println!("main is called {:?}", thread::current().name());
let handle = thread::Builder::new()
.name(String::from("loader"))
.spawn(|| {
let me = thread::current();
println!("inside: {:?}", me.name());
})
.unwrap();
handle.join().unwrap();
let plain = thread::spawn(|| {
println!("unnamed: {:?}", thread::current().name());
});
plain.join().unwrap();
}
It prints:
main is called Some("main")
inside: Some("loader")
unnamed: None
Builder::spawn returns a Result, because asking the operating system for a thread can fail. Plain spawn panics in that case instead. The name shows up in panic messages, thread 'loader' instead of thread '<unnamed>', which helps a lot when a program has many threads.
How many threads should you start? std::thread::available_parallelism() returns how many threads the machine can run at the same time, as a Result. The number depends on the machine, so we won’t print it here. It’s a sensible default for how many pieces to split work into.
Worked example: summing a million numbers in four chunks
We split a big vector into four pieces, sum each piece on its own thread, and add the four results. A scope lets every thread borrow its piece of numbers directly:
use std::thread;
fn main() {
let numbers: Vec<u64> = (1..=1_000_000).collect();
let chunk_size = numbers.len().div_ceil(4);
let partial_sums: Vec<u64> = thread::scope(|s| {
let mut handles = Vec::new();
for chunk in numbers.chunks(chunk_size) {
handles.push(s.spawn(|| chunk.iter().sum::<u64>()));
}
handles.into_iter().map(|h| h.join().unwrap()).collect()
});
for (i, part) in partial_sums.iter().enumerate() {
println!("chunk {i}: {part}");
}
let total: u64 = partial_sums.iter().sum();
println!("total: {total}");
println!("check: {}", numbers.iter().sum::<u64>());
}
It prints:
chunk 0: 31250125000
chunk 1: 93750125000
chunk 2: 156250125000
chunk 3: 218750125000
total: 500000500000
check: 500000500000
Step by step:
div_ceil(4)divides and rounds up, so four chunks always cover every item, even when the length doesn’t divide evenly.numbers.chunks(chunk_size)gives&[u64]slices that borrownumbers. No data is copied.- Each
s.spawngets a closure that reads onechunk. The closure doesn’t borrow the loop variablechunk, which is gone after each pass. It borrows the slice thatchunkpoints to, insidenumbers. That borrow lasts as long asnumbers, and the scope makes it safe. - The scope’s closure returns the
Vecof results, andscopepasses it back out.scopereturns whatever its closure returns. - The order is fixed, because we join in the order we spawned.
The last line checks the answer on one thread. Whether four threads are faster than one depends on the machine and the size of the work. Starting a thread has a cost, and for a small vector one thread wins. Measure before you assume.
Worked example: two threads, one counter
We count “yes” votes, half the list on each thread. The first try has both threads add to the same counter:
use std::thread;
fn main() {
let votes = ["yes", "no", "yes", "yes", "no", "yes"];
let (first, second) = votes.split_at(votes.len() / 2);
let mut yes = 0;
thread::scope(|s| {
s.spawn(|| {
for vote in first {
if *vote == "yes" {
yes += 1;
}
}
});
s.spawn(|| {
for vote in second {
if *vote == "yes" {
yes += 1;
}
}
});
});
println!("yes votes: {yes}");
}
It prints:
error[E0499]: cannot borrow `yes` as mutable more than once at a time
...
16 | s.spawn(|| {
| ^^ second mutable borrow occurs here
...
19 | yes += 1;
| --- second borrow occurs due to use of `yes` in closure
How to read it:
- E0499 is the “one writer” rule from Part 7. Each closure changes
yes, so each captures&mut yes. - The first
&mutlives as long as the first thread. The second closure asks for another&mutwhile the first is still in use. - In a single thread, this rule stops confusing code. Across threads, it stops a data race. Both threads could read
yesas 2, both add 1, and both write 3, losing a vote. The compiler refuses before that can happen.
The fix that needs nothing new: don’t share the counter. Each thread counts its own half and returns the number, and main adds them:
use std::thread;
fn count_yes(votes: &[&str]) -> usize {
votes.iter().filter(|vote| **vote == "yes").count()
}
fn main() {
let votes = ["yes", "no", "yes", "yes", "no", "yes"];
let (first, second) = votes.split_at(votes.len() / 2);
let yes = thread::scope(|s| {
let a = s.spawn(|| count_yes(first));
let b = s.spawn(|| count_yes(second));
let a = a.join().unwrap();
let b = b.join().unwrap();
println!("first half: {a}, second half: {b}");
a + b
});
println!("yes votes: {yes}");
}
It prints:
first half: 2, second half: 2
yes votes: 4
Returning results is the simplest kind of thread code, and it’s worth trying first. When threads really must change one shared value, you need a lock or an atomic counter. Part 24 covers both.
Tips and traps
- E0373, “closure may outlive the current function”. You passed a borrowing closure to
thread::spawn. Addmoveif the thread can own the data. If you need the data afterwards and the thread should end before you go on, usethread::scopeinstead. - Forgetting to join. The program ends when
mainreturns, and unjoined threads are cut off with their work half done. Keep everyJoinHandlewhose result you need, andjoinit. - “
Rc<...>cannot be sent between threads safely” (E0277). AnRcis somewhere in what the closure captures, maybe deep inside a struct. Switch toArcfor shared ownership across threads. - “cannot be shared between threads safely” (E0277). A
CellorRefCellis being shared by&. Use aMutex, anRwLockor an atomic from Part 24, or give each thread its own value. - Printing from threads in tests or tutorials. Lines from different threads come out in a different order on different runs. Return values from threads and print them in
main, in a fixed order. - Using
sleepto wait for a thread. Athread::sleeplong enough on your machine is too short on a busy one. Wait withjoin, never with a timer. - Splitting tiny work. A thread costs memory and start-up time. Four threads to add ten numbers is slower than one loop. Split work only when each piece is big.
A thread may use only what it owns or what outlives it, and the compiler checks both before the program runs.
Exercises
Exercise 1. This program fails with E0373. Fix it in two ways: first with move, then with thread::scope so that main can still print words after the thread is done.
use std::thread;
fn main() {
let words = vec![String::from("red"), String::from("green")];
let handle = thread::spawn(|| {
println!("{} words", words.len());
});
handle.join().unwrap();
}
It prints:
error[E0373]: closure may outlive the current function, but it borrows `words`, which is owned by the current function
Exercise 2. Without running it, predict what this prints. Dividing an integer by zero panics.
let mut handles = Vec::new();
for x in [5, 0, 2] {
handles.push(thread::spawn(move || 10 / x));
}
for handle in handles {
match handle.join() {
Ok(n) => println!("ok: {n}"),
Err(_) => println!("a thread panicked"),
}
}
Exercise 3. Given three sentences in an array, use scoped threads to count the words in each sentence, one thread per sentence. Print the counts in the same order as the sentences, every run. split_whitespace().count() counts the words in a &str.
Answers
1. With move, the thread owns words. If main wants the vector back, the thread can return it, and join hands it over:
use std::thread;
fn main() {
let words = vec![String::from("red"), String::from("green")];
let handle = thread::spawn(move || {
println!("{} words", words.len());
words
});
let words = handle.join().unwrap();
println!("back in main: {words:?}");
}
It prints:
2 words
back in main: ["red", "green"]
That works, but it’s the “hand it back” style that Part 6 called clumsy. With a scope, the thread borrows it, and main gets it back when the scope ends, even to change it:
use std::thread;
fn main() {
let mut words = vec![String::from("red"), String::from("green")];
thread::scope(|s| {
s.spawn(|| {
println!("{} words", words.len());
});
});
words.push(String::from("blue"));
println!("after the scope: {words:?}");
}
It prints:
2 words
after the scope: ["red", "green", "blue"]
2. The thread with x = 0 panics, and its join returns Err. The other two return normally. main joins in the order it spawned, so the lines come out in that order every time:
use std::thread;
fn main() {
let mut handles = Vec::new();
for x in [5, 0, 2] {
handles.push(thread::spawn(move || 10 / x));
}
for handle in handles {
match handle.join() {
Ok(n) => println!("ok: {n}"),
Err(_) => println!("a thread panicked"),
}
}
}
It prints:
ok: 2
a thread panicked
ok: 5
The panic message, “attempt to divide by zero”, goes to standard error, not into this output.
3. Spawn one scoped thread per sentence, keep the handles in a Vec, and join them in order. Each thread borrows its sentence, as each thread borrowed its chunk in the worked example:
use std::thread;
fn main() {
let sentences = ["the cat sat", "threads run side by side", "join waits"];
let counts: Vec<usize> = thread::scope(|s| {
let handles: Vec<_> = sentences
.iter()
.map(|line| s.spawn(|| line.split_whitespace().count()))
.collect();
handles.into_iter().map(|h| h.join().unwrap()).collect()
});
for (line, n) in sentences.iter().zip(&counts) {
println!("{n} words: {line}");
}
}
It prints:
3 words: the cat sat
5 words: threads run side by side
2 words: join waits
The collect into a Vec of handles matters. Without it, the iterator is lazy (Part 17): each thread would be spawned and then joined before the next one starts, and the threads would run one after another.
What’s next
So far our threads have either owned their data or borrowed it read-only, or split it into pieces. In Part 24, threads share one value and change it, with Arc<Mutex<T>>, atomics, and channels that pass messages between threads, and we’ll see a deadlock happen on purpose.