Sub topic 1
Threads and move closures: the starting point
Prerequisites
This chapter assumes you already know:
- Rust ownership and borrowing, including what it means for a value to be moved.
- How closures capture variables, and what the
movekeyword changes. Result,unwrapand basic pattern matching.
You do not need any prior threading experience beyond having seen thread::spawn.
Spawning a thread
std::thread::spawn starts a new operating system thread and runs a closure on it. It returns a JoinHandle<T>, where T is the closure's return value. Calling join blocks until the thread finishes and gives back Result<T, _>. The Err case means the thread panicked.
use std::thread;
fn main() {
let handle = thread::spawn(|| {
println!("hello from the worker");
42
});
let answer = handle.join().unwrap();
println!("worker returned {}", answer);
}Why the closure must own its data
The signature of spawn requires the closure to be Send + 'static. The 'static bound matters here. The compiler cannot know how long the new thread will run. It might outlive the function that created it, so the closure may not borrow from that function's stack.
This code is rejected with error E0373, "closure may outlive the current function":
use std::thread;
fn main() {
let numbers = vec![1, 2, 3];
// Does not compile: the closure borrows `numbers`.
let handle = thread::spawn(|| {
println!("{:?}", numbers);
});
handle.join().unwrap();
}Adding move makes the closure take ownership of numbers. The thread then carries its data with it:
use std::thread;
fn main() {
let numbers = vec![1, 2, 3];
let handle = thread::spawn(move || {
let sum: i32 = numbers.iter().sum();
sum
});
println!("sum = {}", handle.join().unwrap());
// `numbers` has been moved; using it here would not compile.
}Moving into several threads
Ownership can only go to one place. If you try to move the same Vec into two closures, the compiler reports "use of moved value". One workaround is to clone the data for each thread:
use std::thread;
fn main() {
let original = vec![1, 2, 3];
let handles: Vec<_> = (0..3)
.map(|i| {
let mut copy = original.clone();
thread::spawn(move || {
copy.push(i);
copy.len()
})
})
.collect();
for handle in handles {
println!("worker saw {} items", handle.join().unwrap());
}
println!("original is still {:?}", original);
}Each worker prints 4, and original stays [1, 2, 3]. Every thread changed its own private copy, so none of the changes reached the other threads or the main thread.
What comes next
Cloning gives each thread independent data. That is safe, but it is not sharing. If the threads must all update one value, such as a single counter or a single log, copies cannot help. Sharing a mutable value is where the borrow rules and the 'static bound begin to get in the way. The next chapters introduce Arc and Mutex to solve that problem.
Exercise
Why does thread::spawn(|| println!("{:?}", v)) fail to compile when v is a local Vec, and what is the smallest change that fixes it?
Show answer
The closure only borrows v, but spawn requires a 'static closure because the thread may outlive the function that owns v. Writing move || makes the closure take ownership of v, which satisfies the bound. After that, v can no longer be used in the original function.