liveBook · Manning

Blocking

As explained in Code Like a Pro in Rust

A blocking operation is an operation that prevents an asynchronous runtime from switching tasks for a significant period.

An operation blocks an asynchronous runtime when it prevents the scheduler from switching tasks for a significant time. I/O can block while it waits on factors outside the program’s control; sufficiently long CPU-bound work can block too. What counts as “long” depends on context. section 8.3

Use yield points to give control back to the scheduler. Waiting on a future can provide that opportunity; in ordinary async code, this commonly takes the form of `.await`. The aim is to let other tasks run during waits rather than execute every task sequentially. section 8.3 section 8.2

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!");
        });
}

A Tokio current-thread runtime runs a one-second timer with `tokio::time::sleep(duration).await`, making the yield point visible in the code. section 8.3

Do not treat async as a blanket speedup: its advantage is clearest when waiting for I/O takes much longer than processing the result. Check long CPU-bound work as well as I/O when a task leaves the runtime too little opportunity to switch. section 8.2 section 8.3

How Code Like a Pro in Rust covers it

How deep it goes
Defines blocking by its effect on scheduling and explains yield points, but gives no universal duration threshold.
Examples
Contrasts one-second `std::thread::sleep` with an awaited Tokio timer and uses a 1,024-byte I/O timing command.
What it assumes
Assumes familiarity with Rust functions while demonstrating a Tokio runtime and `.await` in a short timer example.
What you can do after
Apply it via Tokio’s awaited timer to create a scheduler yield opportunity instead of sleeping the thread.
How it connects
Connects blocking to synchronous I/O, asynchronous I/O, futures, scheduler yield points, and CPU-bound work.

Also explained in

Compare how 9 books explain blocking →

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.