rust 44 lines · 8 steps

A worker thread driven by Rust channels

Two mpsc channels let a main thread feed jobs to a worker and collect results back, with a Stop message for clean shutdown.

Explained by highlit
1use std::sync::mpsc;
2use std::thread;
3use std::time::Duration;
4 
5enum Job {
6 Compute(u64),
7 Stop,
8}
9 
10fn worker(rx: mpsc::Receiver<Job>, results: mpsc::Sender<u64>) {
11 while let Ok(job) = rx.recv() {
12 match job {
13 Job::Compute(n) => {
14 let sum = (1..=n).sum();
15 thread::sleep(Duration::from_millis(10));
16 if results.send(sum).is_err() {
17 break;
18 }
19 }
20 Job::Stop => break,
21 }
22 }
23}
24 
25fn run(inputs: Vec<u64>) -> Vec<u64> {
26 let (job_tx, job_rx) = mpsc::channel::<Job>();
27 let (res_tx, res_rx) = mpsc::channel::<u64>();
28 
29 let handle = thread::spawn(move || worker(job_rx, res_tx));
30 
31 let count = inputs.len();
32 for n in inputs {
33 job_tx.send(Job::Compute(n)).expect("worker dropped");
34 }
35 job_tx.send(Job::Stop).expect("worker dropped");
36 
37 let mut collected = Vec::with_capacity(count);
38 for _ in 0..count {
39 collected.push(res_rx.recv().expect("sender dropped"));
40 }
41 
42 handle.join().expect("worker panicked");
43 collected
44}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A dedicated Stop variant gives the worker an explicit, race-free signal to finish rather than relying on disconnection alone.
  2. 2Pairing a job channel with a results channel turns thread communication into two clean one-way streams.
  3. 3Counting how many results you expect lets the collector block exactly the right number of times without guessing.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A worker thread driven by Rust channels — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code