Run jobs on N worker threads and collect their results over one channel
Write run_workers: it splits jobs among workers threads, each thread squares its jobs and sends (job, job * job) back to the caller over one mpsc channel, and the function returns the pairs in the order they arrived.
Requirements:
- Every job is processed exactly once;
workers >= 1. - All results travel through a single channel; the caller does not read thread results via
join. - The function returns once every worker is done and never hangs.
mainstays as it is and prints10 385.
use std::sync::mpsc;
use std::thread;
fn run_workers(jobs: Vec<u64>, workers: usize) -> Vec<(u64, u64)> {
// your code here
}
fn main() {
let jobs: Vec<u64> = (1..=10).collect();
let results = run_workers(jobs, 3);
let total: u64 = results.iter().map(|&(_, sq)| sq).sum();
println!("{} {total}", results.len());
}Write the implementation.
Make one mpsc::channel, split the jobs among N threads and move a clone of tx into each to send results. Drop the original tx in the caller; rx.iter().collect() then gathers them in arrival order and ends after the last worker.
- Forgetting
drop(tx)in the caller, sorx.iter()waits forever after the workers finish - Expecting the results in job order, though messages from different senders interleave by timing
- Cloning
txonce before the loop, so the second iteration hits E0382 on the moved clone
- How would you let idle workers pull the next job from one shared queue instead of a fixed share?
- What would
mpsc::sync_channeladd if the caller were much slower than the workers?
Each worker gets its own share of the jobs and its own clone of tx; the clone moves into the thread together with the share. The original tx is dropped after the loop: otherwise the channel would stay open and rx.iter() would wait forever.
use std::sync::mpsc;
use std::thread;
fn run_workers(jobs: Vec<u64>, workers: usize) -> Vec<(u64, u64)> {
let (tx, rx) = mpsc::channel();
let mut queues: Vec<Vec<u64>> = vec![Vec::new(); workers];
for (i, job) in jobs.into_iter().enumerate() {
queues[i % workers].push(job);
}
for queue in queues {
let tx = tx.clone();
thread::spawn(move || {
for job in queue {
tx.send((job, job * job)).unwrap();
}
});
}
drop(tx);
rx.iter().collect()
}
fn main() {
let jobs: Vec<u64> = (1..=10).collect();
let results = run_workers(jobs, 3);
let total: u64 = results.iter().map(|&(_, sq)| sq).sum();
println!("{} {total}", results.len()); // 10 385
}No join is needed here: a thread drops its clone of tx when it finishes, and the last such clone closes the channel, so the receiving loop itself waits for every worker. The order of the pairs changes from run to run, which is why main prints only the count and the sum. When jobs differ in length, a fixed share leaves workers idle: then the jobs go into a second channel whose Receiver is shared through Arc<Mutex<Receiver<u64>>>, and a free worker takes the next one itself.