use std::thread;
fn main() {
let data = vec![1u64, 2, 3, 4, 5];
// Spawn — must move ownership of `data` into the thread
let handle = thread::spawn(move || {
data.iter().sum::<u64>()
});
// Caller does other work concurrently…
println!("main thread doing other stuff");
// Wait + collect the return value
let total = handle.join().unwrap();
println!("sum = {total}");
// Pool of N workers — collect handles, then join them all
let handles: Vec<_> = (0..4).map(|i| {
thread::spawn(move || {
println!("worker {i}");
i * 100
})
}).collect();
let results: Vec<i32> = handles.into_iter().map(|h| h.join().unwrap()).collect();
println!("{results:?}");
}
Create a free account and build your private vault. Share publicly whenever you want.