On this page
  1. Concurrent Worker Pool with Channels
  2. Multi-Threaded Fan-Out with std::thread & mpsc

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