spawn_blocking

Function spawn_blocking 

Source
pub fn spawn_blocking<C, T>(callable: C) -> JoinHandle<T> 
where C: FnOnce() -> T + Send + 'static, T: Send + 'static,
Expand description

Runs the provided closure on a web worker(thread) where blocking is acceptable.

In general, issuing a blocking call or performing a lot of compute in a future without yielding is problematic, as it may prevent the JavaScript runtime from driving other futures forward. This function runs the provided closure on a web worker dedicated to blocking operations.

More and more web workers will be spawned when they are requested through this function until the upper limit of 512 is reached. After reaching the upper limit, the tasks will wait for any of the web workers to become idle. When a web worker remains idle for 10 seconds, it will be terminated and get removed from the worker pool, which is a similiar behavior to that of tokio. The web worker limit is very large by default, because spawn_blocking is often used for various kinds of IO operations that cannot be performed asynchronously. When you run CPU-bound code using spawn_blocking, you should keep this large upper limit in mind.

This function is intended for non-async operations that eventually finish on their own. Because web workers do not share memory like threads do, synchronization primitives such as mutex, channels, and global static variables might not work as expected. Each web worker is completely isolated because that’s how the web works.

§Examples

Pass an input value and receive result of computation:

// Initial input
let mut data = "Hello, ".to_string();
let output = async_wasm_task::spawn_blocking(move || {
    // Stand-in for compute-heavy work or using synchronous APIs
    data.push_str("world");
    // Pass ownership of the value back to the asynchronous context
    data
}).await?;

// `output` is the value returned from the thread
assert_eq!(output.as_str(), "Hello, world");
Ok(())
}