liveBook · Manning

Busy-waiting loop

As explained in Rust in Action: Systems programming concepts and techniques

A spin loop repeatedly checks a condition while actively consuming CPU time instead of blocking execution.

A busy-waiting loop, also called a busy loop or spin loop, waits by repeatedly checking elapsed time instead of suspending the thread with the operating system. In Rust, the loop can call thread::yield_now() while it waits. section 10.2.5

Use the technique when short, timing-sensitive pauses matter, but account for its costs:

  • Improve short-wait timing compared with sleep, which is not perfectly accurate. section 10.2.4
  • Combine sleep for most of a delay with spinning near the end when appropriate. section 10.2.4
  • Avoid assuming that CPU-intensive threading scales beyond the number of physical cores; performance degrades quickly after that point. section 10.2.4

A 20-millisecond spin loop

Record the start time, set a 20-millisecond duration, and repeatedly yield the current thread until the duration has elapsed: while start.elapsed() < pause { thread::yield_now(); }. Spawn this work in threads, then remove and join each handler with while let Some(handle) = handlers.pop().

How Rust in Action: Systems programming concepts and techniques covers it

How deep it goes
Implements elapsed-time polling, thread yielding, joining, a broken borrowing variant, and scalability limits across CPU cores.
Examples
Demonstrates a 20-millisecond Rust wait, compares it with thread::sleep, and reproduces timing data across up to 1,000 threads.
What it assumes
Uses Rust threads, JoinHandle values, Instant, Duration, vectors, and ownership-aware iteration and removal.
What you can do after
Build it from scratch in Rust, benchmark it against sleep, and diagnose ownership errors when joining stored thread handlers.
How it connects
Connects busy-waiting loops to thread sleeping, thread yielding, thread joining, and CPU-core contention.

Also explained in

Compare how 3 books explain busy-waiting loop →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Rust in Action: Systems programming concepts and techniques. The section links point to the parts of the book it draws on.