Worker Pool Shares One Receiver Via Mutex

Share one mpsc receiver across workers through Arc<Mutex>: each thread locks only to pull the next job and exits when the channel closes.

RustResilience

Code

rustsnippet
37 lines
use std::sync::{mpsc, Arc, Mutex};
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel::<i32>();
    // worker pool: shares one receiver, every worker locks briefly to pull the next job
    let rx = Arc::new(Mutex::new(rx));

    let workers: Vec<_> = (0..3)
        .map(|id| {
            let rx = Arc::clone(&rx);
            thread::spawn(move || {
                let mut done = Vec::new();
                loop {
                    // 锁只覆盖 recv,处理任务前已释放
                    let job = { let guard = rx.lock().unwrap(); guard.recv() };
                    match job {
                        Ok(n) => done.push(format!("worker {id} handled {n}")),
                        Err(_) => break, // 通道关闭且已清空
                    }
                }
                done
            })
        })
        .collect();

    for n in 1..=5 {
        tx.send(n).unwrap();
    }
    drop(tx); // 关闭发送端,worker 清空队列后自然退出

    for worker in workers {
        for line in worker.join().unwrap() {
            println!("{line}");
        }
    }
}

What the code does

Worker Pool Shares One Receiver Via Mutex comes down to the function main.

Repetition is confined to for n in 1..=5 — the rest of the file is straight-line. Pattern matching via match forces each shape of the value to be handled.

Watch out for

  • Nothing third-party is pulled in; the snippet is dependency-free.

Statements that carry the weight

Err(_) => break, // 通道关闭且已清空
}
let job = { let guard = rx.lock().unwrap(); guard.recv() };
for line in worker.join().unwrap() {
    println!("{line}");
}

Interactive Tools for This Topic

FAQ

How do you run Worker Pool Shares One Receiver Via Mutex?
Run the file on its own; every call resolves against the standard surface it already imports.