rust
28 lines · 7 steps
Running work with a timeout in Rust
Run a closure on a separate thread and give up if it doesn't finish in time, using a channel's timed receive.
Explained by
highlit
1use std::sync::mpsc;
2use std::thread;
3use std::time::Duration;
4
5#[derive(Debug)]
6pub enum ComputeError {
7 Timeout,
8 Panicked,
9}
10
11pub fn compute_with_timeout<T, F>(timeout: Duration, work: F) -> Result<T, ComputeError>
12where
13 T: Send + 'static,
14 F: FnOnce() -> T + Send + 'static,
15{
16 let (tx, rx) = mpsc::channel();
17
18 thread::spawn(move || {
19 let result = work();
20 let _ = tx.send(result);
21 });
22
23 match rx.recv_timeout(timeout) {
24 Ok(value) => Ok(value),
25 Err(mpsc::RecvTimeoutError::Timeout) => Err(ComputeError::Timeout),
26 Err(mpsc::RecvTimeoutError::Disconnected) => Err(ComputeError::Panicked),
27 }
28}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A channel's recv_timeout turns "wait for a result" into "wait, but bounded" without polling.
- 2A dropped sender surfaces as a Disconnected error, letting you detect a thread that died before sending.
- 3Send + 'static bounds are what make it safe to move a value across a thread boundary.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 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
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/running-work-with-a-timeout-in-rust-explained-rust-4b09/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.