Rust
Beginner
1 min read
Threads and the Send and Sync Traits
Example
use std::thread;
use std::time::Duration;
fn main() {
// Spawn a thread with a move closure
let data = vec![1, 2, 3, 4, 5];
let handle = thread::spawn(move || {
println!("thread sees: {:?}", data);
let sum: i32 = data.iter().sum();
sum // return value from the thread
});
// Main thread continues
println!("main thread is running");
// Wait for the spawned thread to finish and get its result
let sum = handle.join().expect("thread panicked");
println!("thread computed sum = {sum}");
// Spawn multiple threads
let handles: Vec<_> = (0..5).map(|i| {
thread::spawn(move || {
thread::sleep(Duration::from_millis(50 * i));
println!("thread {i} done");
i * i
})
}).collect();
let results: Vec<u64> = handles.into_iter()
.map(|h| h.join().unwrap())
.collect();
println!("squares: {:?}", results);
// thread::Builder for named threads
let builder = thread::Builder::new().name("worker".to_string());
let worker = builder.spawn(|| {
println!("I am thread '{}'", thread::current().name().unwrap_or("?"));
}).unwrap();
worker.join().unwrap();
}