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 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
ruby
class TemplateInterpolator PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/ def initialize(strict: false)
Interpolating templates with dotted keys in Ruby
regex
string-interpolation
hash-traversal
Intermediate
6 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
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
typescript
import { parsePhoneNumberFromString, CountryCode } from 'libphonenumber-js'; export interface NormalizedPhone { e164: string;
Normalizing phone numbers to E.164 in TypeScript
validation
normalization
error-handling
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.