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 serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 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.