Skip to content

Search is only available in production builds. Try building and previewing the site to test it out locally.

Test MDX File V10

Thread Lifecycle

Rust Thread Lifecycle

🛰️

Edge AI Scenario

An edge device spawns a sensor thread that reads a sensor, runs inference on the sample, then sleeps for 50 ms before repeating. Meanwhile main waits on handle.join(). Both threads share a single CPU core — the OS scheduler decides who runs when.

The program

PC @ line 4 · executing here

use std::thread;
use std::time::Duration;
 
fn main() {
let handle = thread::spawn(|| {
for _ in 0..2 {
let sample = read_sensor(); // I/O
let _label = run_inference(sample); // compute
thread::sleep(Duration::from_millis(50));
}
});
handle.join().unwrap();
}

The five lifecycle states

hover or tap a state for detail

CPU Core 0
Currently executing
main thread

Wall clock

000 ms

Context switches

0 switches · ~0 µs cost

Lifecycle timeline

each cell = 5 ms · total 320 ms

main threadfn main() { … handle.join() }
Running
sensor threadthread::spawn(|| { read · infer · sleep })
not yet spawned
080160240320
Speed
0 ms320 ms

What just happened

t = 000 msmain

main starts running

Jump to event

Real-time takeaway

Every context switch costs roughly 1–10 µs on modern hardware as registers are saved and restored. On hard real-time edge systems with tight deadlines, this overhead must be budgeted alongside the work the threads do. Excessive blocking and waking — chatty I/O, fine-grained locks, short sleeps — multiplies the switch count quickly.