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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A dedicated Stop variant gives the worker an explicit, race-free signal to finish rather than relying on disconnection alone.
- 2Pairing a job channel with a results channel turns thread communication into two clean one-way streams.
- 3Counting how many results you expect lets the collector block exactly the right number of times without guessing.
Related explainers
rust
use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::thread;
Aggregating metrics across threads in Rust
concurrency
shared-state
mutex
Intermediate
7 steps
java
public class ThumbnailProcessor { private static final int MAX_CONCURRENCY = 4;
Bounded parallel thumbnail rendering in Java
concurrency
thread-pool
futures
Intermediate
7 steps
rust
use std::sync::{mpsc, Arc, Mutex}; use std::thread; use std::time::Duration;
Building a thread pool in Rust
concurrency
channels
thread-pool
Advanced
9 steps
go
package cache import ( "container/list"
Building a generic LRU cache in Go
lru-cache
generics
linked-list
Intermediate
8 steps
rust
use std::time::Instant; use tracing::info; pub struct Timer {
A scope-guard timer with Drop in Rust
raii
drop-guard
timing
Intermediate
7 steps
rust
use std::collections::HashMap; pub struct Memoizer<K, V, F> { cache: HashMap<K, V>,
A generic memoizer in Rust
memoization
generics
caching
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-worker-thread-driven-by-rust-channels-explained-rust-4992/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.