sleep pauses the current thread for a requested duration. The request goes to the operating system, which suspends the thread until that time has passed. section 10.2.5
A 20 ms sleep is not perfectly accurate. With many competing threads, scheduling overhead and cache disruption can make the pause take substantially longer. section 10.2.4
Use the waiting strategy that matches the timing requirement:
- Prefer sleep when a thread can yield the processor while it waits. section 10.2.4
- Prefer a spin loop for short, timing-sensitive pauses; combine sleep with spinning when most of the wait can be relaxed. section 10.2.4
- Expect CPU-intensive waiting to degrade once thread counts exceed the number of physical cores. section 10.2.4
Suspending a Rust thread
use std::{thread, time}; let pause = time::Duration::from_millis(20); thread::sleep(pause);
Measuring many sleeping threads
A benchmark can record an Instant, spawn batches of threads that call thread::sleep for 20 ms, join every JoinHandle, and print the elapsed duration. Removing each handle with handlers.pop() permits ownership of the handle to move into join().
