From 0b5761c190031a71faf06bbe758386ed58a910d5 Mon Sep 17 00:00:00 2001 From: Abutalib Aghayev Date: Thu, 27 Oct 2022 15:55:51 -0400 Subject: [PATCH] rt: add a method to determine if the runtime is multi-threaded. --- tokio/src/runtime/handle.rs | 28 +++++++++++++++++++++++++++- tokio/src/runtime/mod.rs | 9 +++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/tokio/src/runtime/handle.rs b/tokio/src/runtime/handle.rs index 91974252610..005f50e0494 100644 --- a/tokio/src/runtime/handle.rs +++ b/tokio/src/runtime/handle.rs @@ -1,4 +1,4 @@ -use crate::runtime::scheduler; +use crate::runtime::{scheduler, Flavor}; /// Handle to the runtime. /// @@ -101,6 +101,32 @@ impl Handle { } } + /// Returns the flavor of the current `Runtime`. + /// + /// ``` + /// use tokio::runtime::{Handle, Flavor}; + /// + /// #[tokio::main(flavor = "current_thread")] + /// async fn main() { + /// assert_eq!(Flavor::CurrentThread, Handle::current().get_flavor()); + /// } + /// ``` + /// + /// ``` + /// use tokio::runtime::{Handle, Flavor}; + /// + /// #[tokio::main(flavor = "multi_thread", worker_threads = 4)] + /// async fn main() { + /// assert_eq!(Flavor::MultiThread, Handle::current().get_flavor()); + /// } + /// ``` + pub fn get_flavor(&self) -> Flavor { + match self.inner { + scheduler::Handle::CurrentThread(_) => Flavor::CurrentThread, + scheduler::Handle::MultiThread(_) => Flavor::MultiThread, + } + } + /// Returns a Handle view over the currently running Runtime /// /// Returns an error if no Runtime has been started diff --git a/tokio/src/runtime/mod.rs b/tokio/src/runtime/mod.rs index b69d696cdef..012cf059ad3 100644 --- a/tokio/src/runtime/mod.rs +++ b/tokio/src/runtime/mod.rs @@ -312,6 +312,15 @@ cfg_rt! { blocking_pool: BlockingPool, } + /// The flavor of the `Runtime`. + #[derive(Debug, PartialEq)] + pub enum Flavor { + /// The flavor that executes all tasks on the current thread. + CurrentThread, + /// The flavor that executes tasks across multiple threads. + MultiThread, + } + /// The runtime scheduler is either a multi-thread or a current-thread executor. #[derive(Debug)] enum Scheduler {