tokio: add Runtime::spawn_blocking (#2980)

This allows writing

rt.spawn_blocking(f);

instead of

let _enter = rt.enter();
tokio::task::spawn_blocking(f);

Signed-off-by: Marc-Antoine Perennou <[email protected]>
This commit is contained in:
Marc-Antoine Perennou
2020-10-19 18:49:16 +02:00
committed by GitHub
parent cfd643d691
commit 2696794771
+27
View File
@@ -187,6 +187,7 @@ cfg_rt! {
mod blocking;
use blocking::BlockingPool;
use blocking::task::BlockingTask;
pub(crate) use blocking::spawn_blocking;
mod builder;
@@ -371,6 +372,32 @@ cfg_rt! {
}
}
/// Run the provided function on an executor dedicated to blocking operations.
///
/// # Examples
///
/// ```
/// use tokio::runtime::Runtime;
///
/// # fn dox() {
/// // Create the runtime
/// let rt = Runtime::new().unwrap();
///
/// // Spawn a blocking function onto the runtime
/// rt.spawn_blocking(|| {
/// println!("now running on a worker thread");
/// });
/// # }
#[cfg(feature = "rt")]
pub fn spawn_blocking<F, R>(&self, func: F) -> JoinHandle<R>
where
F: FnOnce() -> R + Send + 'static,
{
let (task, handle) = task::joinable(BlockingTask::new(func));
let _ = self.handle.blocking_spawner.spawn(task, &self.handle);
handle
}
/// Run a future to completion on the Tokio runtime. This is the
/// runtime's entry point.
///