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

Walkthrough

Space play step click any line
Three takeaways
  1. 1A channel's recv_timeout turns "wait for a result" into "wait, but bounded" without polling.
  2. 2A dropped sender surfaces as a Disconnected error, letting you detect a thread that died before sending.
  3. 3Send + 'static bounds are what make it safe to move a value across a thread boundary.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Running work with a timeout in Rust — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code