Concurrent Worker Pool with Channels
Prev: CLI File Processor with Result & ? | Up: tutorials | Next: Zero-Copy Parsing with Lifetimes
Rel: mpsc, Arc, Mutex, Synchronization & Coordination
Ref: The Rust Book — Fearless Concurrency
Tags: #public #prog #rust #tutorials #concurrency
Multi-Threaded Fan-Out with std::thread & mpsc
use std::sync::{mpsc, Arc, Mutex};
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel::<u64>();
let rx = Arc::new(Mutex::new(rx));
let mut handles = Vec::new();
for worker_id in 0..4 {
let rx = Arc::clone(&rx);
handles.push(thread::spawn(move || {
let mut local_sum = 0;
while let Ok(job) = rx.lock().unwrap().recv() {
local_sum += job * job;
}
(worker_id, local_sum)
}));
}
for n in 1..=20 {
tx.send(n).unwrap();
}
drop(tx); // Closing the sender signals workers to exit
let total: u64 = handles.into_iter().map(|h| h.join().unwrap().1).sum();
println!("total = {total}");
}
Linked from
Related notes
- tuts/rust/tutorials Linked here; links to this page; shared tags: #prog, #rust, #tutorials
- tuts/rust/tutorials/cli_file_processor_with_result Linked here; links to this page; shared tags: #prog, #rust, #tutorials
- tuts/rust/tutorials/zero_copy_parsing_with_lifetimes Linked here; links to this page; shared tags: #prog, #rust, #tutorials
- tuts/programming/concurrency/synchronization_and_coordination Linked here; shared tags: #concurrency, #prog
- tuts/rust/std/smart_pointers/Arc Linked here; shared tags: #prog, #rust
- tuts/rust/std/sync/mpsc Linked here; shared tags: #prog, #rust
- tuts/rust/std/sync/Mutex Linked here; shared tags: #prog, #rust
- tuts/interop/rust_and_python_pyo3_maturin shared tags: #prog, #rust, #tutorials
- tuts/c/tutorials shared tags: #prog, #tutorials
- tuts/c/tutorials/arena_allocator_pattern shared tags: #prog, #tutorials