Thread Park And Unpark Handoff
Hand a signal between threads with thread::park and Thread::unpark, which needs no channel and keeps an unpark that arrives before the park.
Code
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread;
fn main() {
let ready = Arc::new(AtomicBool::new(false));
let flag = Arc::clone(&ready);
// an unpark that arrives before park is remembered as a permit
let worker = thread::spawn(move || {
while !flag.load(Ordering::Acquire) {
thread::park();
}
println!("worker resumed after park");
});
thread::sleep(std::time::Duration::from_millis(20));
ready.store(true, Ordering::Release);
worker.thread().unpark();
worker.join().unwrap();
println!("park/unpark handoff complete");
}How the snippet works
The working surface is the function main — everything else is wiring.
while !flag.load(Ordering::Acquire) is the loop that carries the per-item work.
Caveats
- No package installation, no environment variables, no setup steps.
Using it
The demo output is labeled (worker resumed after park, park/unpark handoff complete), so every printed line maps back to its originating operation.
Key statements
let worker = thread::spawn(move || {
while !flag.load(Ordering::Acquire) {
thread::park();
}
println!("worker resumed after park");
});
worker.join().unwrap();
Interactive Tools for This Topic
FAQ
- What does Thread Park And Unpark Handoff print when run?
- Execute the whole file; each printed line is prefixed with a label like `worker resumed after park`, `park/unpark handoff complete`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.