mirror of
https://github.com/tokio-rs/tokio.git
synced 2026-08-20 00:00:08 +02:00
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:
@@ -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.
|
||||
///
|
||||
|
||||
Reference in New Issue
Block a user