summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMarc-Antoine Perennou <Marc-Antoine@Perennou.com>2020-10-19 18:49:16 +0200
committerGitHub <noreply@github.com>2020-10-19 18:49:16 +0200
commit26967947713cdc3efff7c37146cf72d895a70682 (patch)
treec9bd0f355d817eb3506cb2c02236a209fee3d872
parentcfd643d6911e6b80adae688bbd53e57d7bdb93f2 (diff)
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 <Marc-Antoine@Perennou.com>
-rw-r--r--tokio/src/runtime/mod.rs27
1 files changed, 27 insertions, 0 deletions
diff --git a/tokio/src/runtime/mod.rs b/tokio/src/runtime/mod.rs
index 25b20de8..7f4952d7 100644
--- a/tokio/src/runtime/mod.rs
+++ b/tokio/src/runtime/mod.rs
@@ -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.
///