liveBook · Manning

Yield point

As explained in Code Like a Pro in Rust

A yield point is a point in code that passes control back to an asynchronous task scheduler.

A yield point passes control back to the asynchronous task scheduler, allowing the runtime to switch tasks instead of waiting on one operation for too long. section 8.3

Use yield points to keep async execution responsive:

  • Waiting on or joining a future creates a yield point by passing control through the future chain to the runtime. section 8.3
  • Treat I/O as a likely blocking operation, and recognize that sufficiently long CPU-bound work can also block task switching. section 8.3
  • Judge whether work is too slow contextually: a small file read can take orders of magnitude longer than an ordinary function call. section 8.3
fn main() {
    use std::time;
 
    let duration = time::Duration::from_secs(1);
 
    tokio::runtime::Builder::new_current_thread()
        .enable_time()                             #1
        .build()
        .unwrap()
        .block_on(async {                          #2
            tokio::time::sleep(duration).await;
            println!("Hello, world!");
        });
}

Compare synchronous sleeping with Tokio async sleeping: awaiting the timer gives the runtime a scheduling opportunity. section 8.3

How Code Like a Pro in Rust covers it

How deep it goes
Defines scheduler handoff and compares operation timings, but stops short of hard thresholds for excessive blocking.
Examples
Uses future waiting, Tokio timer awaiting, synchronous sleeping, and a 1,024-byte file-read timing comparison.
What it assumes
Assumes familiarity with futures, asynchronous tasks, runtimes, and the distinction between I/O-bound and CPU-bound work.
What you can do after
Apply it via async waiting to avoid preventing the runtime from switching tasks during slow operations.
How it connects
Ties futures, asynchronous runtimes, I/O operations, and CPU-bound work to cooperative task scheduling.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Code Like a Pro in Rust. The section links point to the parts of the book it draws on.