Multi-threading support
See also the sync module for synchronization primitives.
Modules
Structs
Functions
-
fn spawn<T, F>(func: F) -> JoinHandle<T>
F: Fn() -> TSpawn a new thread with default settings.
The thread will execute the given function and then terminate.
spawn
returns a JoinHandle, which can be used to join the thread and retreive the value that the thread returned.See Builder as a means to customize thread creation options.
Example
use std::thread::{spawn, sleep}; use std::time::Duration; let text = "The quick brown fox jumps over the lazy dog"; let t = spawn(|=text| -> usize { // pretend that calculating the length is expensive sleep(Duration::from_secs(1)); text.len() }); println!("Calculating length of {}", text); println!("Length is {}", t.join().unwrap());
Run this examplePanic handling
If the child thread panics, the process is not terminated automatically. Instead, the join function will return a JoinError with the panic information.
If a thread is detached, a panic in the thread will terminate the process.
-
fn sleep(duration: Duration)
Suspends thread execution for the specified duration.
The sleep may sleep for less than the specified time if interrupted by a signal.
Example
use std::time::{Instant, Duration}; use std::thread::sleep; let start = Instant::now(); sleep(Duration::from_millis(500)); assert!(Instant::now().duration_since(&start).total_secs() >= 0.5);
Run this example -
Yields the execution of the current thread.
You probably don't want to use this in a spin-lock.
Example
use std::time::Duration; /// A bad way to sleep. Use std::thread::sleep instead fn bad_sleep(duration: Duration) { use std::time::Instant; use std::thread::yield_thread; let start = time::Instant::now(); while Instant::now().duration_since(&start) < duration { yield_thread(); } } bad_sleep(Duration::from_millis(10));
Run this example