Rust Reference ยท Standard Library Modules
The std::thread module
Reference for std::thread: spawn and JoinHandle, join results and panics, scoped threads, Builder, sleep, yield_now, park, available_parallelism and thread_local.
std::thread creates operating-system threads. thread::spawn starts a new thread running a closure and returns a JoinHandle; calling join on the handle waits for the thread and gives you its return value, or its panic. Because a spawned thread can outlive the function that created it, the closure must be 'static and usually moves its captured data.
Scoped threads (thread::scope) relax that rule: threads started inside the scope are all joined before it returns, so they may borrow local variables. The module also has sleep, park/unpark, yield_now, current, Builder for naming threads and sizing stacks, and the thread_local! macro.
use std::thread; let handle = thread::spawn(|| 6 * 7); let answer = handle.join().unwrap();
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
| Item | Description |
|---|---|
spawn<F, T>(f: F) -> JoinHandle<T> |
F: FnOnce() -> T + Send + 'static, T: Send + 'static. Panics if the OS cannot create a thread. |
JoinHandle::join(self) -> Result<T, Box<dyn Any + Send>> |
Wait; Err carries the panic payload. |
JoinHandle::is_finished(), .thread() |
Poll without blocking; get the Thread handle. |
scope(|s| ...) -> R |
Run a closure that can s.spawn(...); all spawned threads are joined before it returns. |
Builder::new().name(..).stack_size(..).spawn(..) |
Like spawn, but returns io::Result<JoinHandle<T>>. |
sleep(Duration) |
Block the current thread at least that long. |
yield_now() |
Hint to let another thread run. |
park(), Thread::unpark() |
Block until a token is available; spurious wake-ups are possible. |
current() -> Thread |
Handle with name() and id(). |
available_parallelism() -> io::Result<NonZero<usize>> |
A hint for how many threads can run at once. |
thread_local! |
Declare per-thread statics, accessed with .with(|v| ...). |
Errors and edge cases: a panic in a thread unwinds that thread only. The main thread ending ends the whole process, killing other threads without joining them. Unjoined JoinHandles detach their thread.
Usage notes
- Everything moved into a spawned thread must be
Send.RcandRefCell-based sharing fails to compile; useArc,Mutexand channels instead. - Prefer
thread::scopewhen threads only need to finish before the function returns; it avoidsArcand cloning. - Output order between threads is unspecified. Join and collect results (or use channels) before printing when you need determinism.
joinon a panicked thread returnsErr; calling.unwrap()on it re-panics the joiner, which is often what you want.- Creating a thread costs microseconds and a stack (2 MiB virtual by default), so use a pool or
scopefor many small tasks. sleepis not a synchronization tool; use channels,Condvarorparkto wait for events.available_parallelismcan return an error or a value smaller than the physical core count (containers, affinity).
Related
- std::sync, std::sync::mpsc, std::sync::atomic
- Send and Sync, Arc, move
- Tutorial: Threads, Send and Sync