Skip to main content

spawn_blocking

Function spawn_blocking 

Source
pub fn spawn_blocking<T: Send + 'static>(
    job: impl FnOnce() -> T + Send + 'static,
) -> Blocking<T> ⓘ
Expand description

Run job on a pool thread and resolve to its value on the awaiting side.

The one bridge from an async flow to a call that blocks or computes for a while: a file read, a parse, a hash, a database open, a block_on into some other runtime. The pool is process-wide, starts with the first job, holds at most blocking_limit threads, and lets a thread go after a few idle seconds; jobs beyond the limit queue in order. Nothing here knows about Day’s executor, so a part can await it under day::task or a test’s block_on alike.

On the web, where no thread exists, the job runs inline at the future’s first poll. Keep web jobs short, or branch on cfg!(target_arch = "wasm32") and use the platform’s async API. A synchronous test harness (the mock toolkit) asks for the same with set_blocking_inline.

ⓘ
let bytes = day::spawn_blocking(move || std::fs::read(&path)).await;
match bytes {
    Ok(Ok(bytes)) => contents.set(bytes),
    Ok(Err(io)) => status.set(io.to_string()),
    Err(e) => status.set(e.to_string()),
}