Rust: Concurrency – code examples
Contents
Distributing a computation across threads
Concurrency#thread#spawn#join#parallel
Use case: Spreading compute-intensive tasks (sums, image processing) across several cores.
use std::thread;
fn main() {
let daten: Vec<u64> = (1..=1000).collect();
let teile: Vec<Vec<u64>> = daten.chunks(500).map(|c| c.to_vec()).collect();
let handles: Vec<_> = teile
.into_iter()
.map(|teil| thread::spawn(move || teil.iter().sum::<u64>()))
.collect();
let summe: u64 = handles.into_iter().map(|h| h.join().unwrap()).sum();
println!("{summe}"); // 500500
}Each thread gets its own part via move; join returns the partial result. For data parallelism in real projects, the rayon crate is worth it.
Shared counter with Arc<Mutex>
Concurrency#arc#mutex#thread#sync
Use case: Sharing state between threads, e.g. statistics or caches in a server.
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let zaehler = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..8 {
let z = Arc::clone(&zaehler);
handles.push(thread::spawn(move || {
*z.lock().unwrap() += 1;
}));
}
for h in handles { h.join().unwrap(); }
println!("{}", *zaehler.lock().unwrap()); // 8
}Arc allows multiple owners across threads, and Mutex serializes access. The guard releases the lock when it leaves the block.
Messages between threads (channel)
Concurrency#channel#mpsc#thread
Use case: Worker threads deliver results to a collector (pipeline, job queue).
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
for id in 0..3 {
let tx = tx.clone();
thread::spawn(move || tx.send(id * 10).unwrap());
}
drop(tx);
let mut ergebnisse: Vec<i32> = rx.iter().collect();
ergebnisse.sort();
println!("{:?}", ergebnisse); // [0, 10, 20]
}Without drop(tx), rx.iter() would wait forever because a sender still exists. The order of arrival is unspecified, hence the sort.