[][src]Function tokio::task::block_in_place

pub fn block_in_place<F, R>(f: F) -> R where
    F: FnOnce() -> R, 

Runs the provided blocking function on the current thread without blocking the executor.

In general, issuing a blocking call or performing a lot of compute in a future without yielding is not okay, as it may prevent the executor from driving other futures forward. This function runs the closure on the current thread by having the thread temporarily cease from being a core thread, and turns it into a blocking thread. See the CPU-bound tasks and blocking code section for more information.

Although this function avoids starving other independently spawned tasks, any other code running concurrently in the same task will be suspended during the call to block_in_place. This can happen e.g. when using the join! macro. To avoid this issue, use spawn_blocking instead.

Note that this function can only be used when using the multi_thread runtime.

Code running behind block_in_place cannot be cancelled. When you shut down the executor, it will wait indefinitely for all blocking operations to finish. You can use shutdown_timeout to stop waiting for them after a certain timeout. Be aware that this will still not cancel the tasks — they are simply allowed to keep running after the method returns.

Examples

use tokio::task;

task::block_in_place(move || {
    // do some compute-heavy work or call synchronous code
});