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 axum::{extract::{Path, State}, http::StatusCode, Json}; use dashmap::DashMap; use serde::Serialize; use std::sync::Arc;
Request coalescing in an Axum handler
caching
concurrency
request-coalescing
Advanced
8 steps
go
package config import ( "fmt"
A thread-safe config singleton in Go
singleton
concurrency
environment-variables
Intermediate
7 steps
rust
use std::net::Ipv4Addr; use std::str::FromStr; #[derive(Debug, Clone, Copy)]
Parsing and matching IPv4 CIDR ranges in Rust
bitwise-operations
parsing
error-handling
Intermediate
8 steps
javascript
const express = require('express'); const app = express(); app.get('/health', (req, res) => res.json({ status: 'ok' }));
Graceful shutdown in an Express server
graceful-shutdown
signal-handling
connection-tracking
Advanced
9 steps
rust
use std::sync::OnceLock; static CRC_TABLE: OnceLock<[u32; 256]> = OnceLock::new();
Table-driven CRC32 with lazy init in Rust
checksums
lazy-initialization
lookup-tables
Intermediate
8 steps
rust
use axum::{ body::Body, extract::Path, http::{header, HeaderMap, HeaderValue, StatusCode},
HTTP range requests for video streaming in Axum
http-range-requests
streaming
async-io
Advanced
8 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.