1 use crate::runtime::{context, scheduler, RuntimeFlavor}; 2 3 /// Handle to the runtime. 4 /// 5 /// The handle is internally reference-counted and can be freely cloned. A handle can be 6 /// obtained using the [`Runtime::handle`] method. 7 /// 8 /// [`Runtime::handle`]: crate::runtime::Runtime::handle() 9 #[derive(Debug, Clone)] 10 // When the `rt` feature is *not* enabled, this type is still defined, but not 11 // included in the public API. 12 pub struct Handle { 13 pub(crate) inner: scheduler::Handle, 14 } 15 16 use crate::runtime::task::JoinHandle; 17 use crate::util::error::{CONTEXT_MISSING_ERROR, THREAD_LOCAL_DESTROYED_ERROR}; 18 19 use std::future::Future; 20 use std::marker::PhantomData; 21 use std::{error, fmt}; 22 23 /// Runtime context guard. 24 /// 25 /// Returned by [`Runtime::enter`] and [`Handle::enter`], the context guard exits 26 /// the runtime context on drop. 27 /// 28 /// [`Runtime::enter`]: fn@crate::runtime::Runtime::enter 29 #[derive(Debug)] 30 #[must_use = "Creating and dropping a guard does nothing"] 31 pub struct EnterGuard<'a> { 32 _guard: context::SetCurrentGuard, 33 _handle_lifetime: PhantomData<&'a Handle>, 34 } 35 36 impl Handle { 37 /// Enters the runtime context. This allows you to construct types that must 38 /// have an executor available on creation such as [`Sleep`] or [`TcpStream`]. 39 /// It will also allow you to call methods such as [`tokio::spawn`] and [`Handle::current`] 40 /// without panicking. 41 /// 42 /// [`Sleep`]: struct@crate::time::Sleep 43 /// [`TcpStream`]: struct@crate::net::TcpStream 44 /// [`tokio::spawn`]: fn@crate::spawn enter(&self) -> EnterGuard<'_>45 pub fn enter(&self) -> EnterGuard<'_> { 46 EnterGuard { 47 _guard: match context::try_set_current(&self.inner) { 48 Some(guard) => guard, 49 None => panic!("{}", crate::util::error::THREAD_LOCAL_DESTROYED_ERROR), 50 }, 51 _handle_lifetime: PhantomData, 52 } 53 } 54 55 /// Returns a `Handle` view over the currently running `Runtime`. 56 /// 57 /// # Panics 58 /// 59 /// This will panic if called outside the context of a Tokio runtime. That means that you must 60 /// call this on one of the threads **being run by the runtime**, or from a thread with an active 61 /// `EnterGuard`. Calling this from within a thread created by `std::thread::spawn` (for example) 62 /// will cause a panic unless that thread has an active `EnterGuard`. 63 /// 64 /// # Examples 65 /// 66 /// This can be used to obtain the handle of the surrounding runtime from an async 67 /// block or function running on that runtime. 68 /// 69 /// ``` 70 /// # use std::thread; 71 /// # use tokio::runtime::Runtime; 72 /// # fn dox() { 73 /// # let rt = Runtime::new().unwrap(); 74 /// # rt.spawn(async { 75 /// use tokio::runtime::Handle; 76 /// 77 /// // Inside an async block or function. 78 /// let handle = Handle::current(); 79 /// handle.spawn(async { 80 /// println!("now running in the existing Runtime"); 81 /// }); 82 /// 83 /// # let handle = 84 /// thread::spawn(move || { 85 /// // Notice that the handle is created outside of this thread and then moved in 86 /// handle.spawn(async { /* ... */ }); 87 /// // This next line would cause a panic because we haven't entered the runtime 88 /// // and created an EnterGuard 89 /// // let handle2 = Handle::current(); // panic 90 /// // So we create a guard here with Handle::enter(); 91 /// let _guard = handle.enter(); 92 /// // Now we can call Handle::current(); 93 /// let handle2 = Handle::current(); 94 /// }); 95 /// # handle.join().unwrap(); 96 /// # }); 97 /// # } 98 /// ``` 99 #[track_caller] current() -> Self100 pub fn current() -> Self { 101 Handle { 102 inner: scheduler::Handle::current(), 103 } 104 } 105 106 /// Returns a Handle view over the currently running Runtime 107 /// 108 /// Returns an error if no Runtime has been started 109 /// 110 /// Contrary to `current`, this never panics try_current() -> Result<Self, TryCurrentError>111 pub fn try_current() -> Result<Self, TryCurrentError> { 112 context::try_current().map(|inner| Handle { inner }) 113 } 114 115 /// Spawns a future onto the Tokio runtime. 116 /// 117 /// This spawns the given future onto the runtime's executor, usually a 118 /// thread pool. The thread pool is then responsible for polling the future 119 /// until it completes. 120 /// 121 /// The provided future will start running in the background immediately 122 /// when `spawn` is called, even if you don't await the returned 123 /// `JoinHandle`. 124 /// 125 /// See [module level][mod] documentation for more details. 126 /// 127 /// [mod]: index.html 128 /// 129 /// # Examples 130 /// 131 /// ``` 132 /// use tokio::runtime::Runtime; 133 /// 134 /// # fn dox() { 135 /// // Create the runtime 136 /// let rt = Runtime::new().unwrap(); 137 /// // Get a handle from this runtime 138 /// let handle = rt.handle(); 139 /// 140 /// // Spawn a future onto the runtime using the handle 141 /// handle.spawn(async { 142 /// println!("now running on a worker thread"); 143 /// }); 144 /// # } 145 /// ``` 146 #[track_caller] spawn<F>(&self, future: F) -> JoinHandle<F::Output> where F: Future + Send + 'static, F::Output: Send + 'static,147 pub fn spawn<F>(&self, future: F) -> JoinHandle<F::Output> 148 where 149 F: Future + Send + 'static, 150 F::Output: Send + 'static, 151 { 152 self.spawn_named(future, None) 153 } 154 155 /// Runs the provided function on an executor dedicated to blocking. 156 /// operations. 157 /// 158 /// # Examples 159 /// 160 /// ``` 161 /// use tokio::runtime::Runtime; 162 /// 163 /// # fn dox() { 164 /// // Create the runtime 165 /// let rt = Runtime::new().unwrap(); 166 /// // Get a handle from this runtime 167 /// let handle = rt.handle(); 168 /// 169 /// // Spawn a blocking function onto the runtime using the handle 170 /// handle.spawn_blocking(|| { 171 /// println!("now running on a worker thread"); 172 /// }); 173 /// # } 174 #[track_caller] spawn_blocking<F, R>(&self, func: F) -> JoinHandle<R> where F: FnOnce() -> R + Send + 'static, R: Send + 'static,175 pub fn spawn_blocking<F, R>(&self, func: F) -> JoinHandle<R> 176 where 177 F: FnOnce() -> R + Send + 'static, 178 R: Send + 'static, 179 { 180 self.inner.blocking_spawner().spawn_blocking(self, func) 181 } 182 183 /// Runs a future to completion on this `Handle`'s associated `Runtime`. 184 /// 185 /// This runs the given future on the current thread, blocking until it is 186 /// complete, and yielding its resolved result. Any tasks or timers which 187 /// the future spawns internally will be executed on the runtime. 188 /// 189 /// When this is used on a `current_thread` runtime, only the 190 /// [`Runtime::block_on`] method can drive the IO and timer drivers, but the 191 /// `Handle::block_on` method cannot drive them. This means that, when using 192 /// this method on a current_thread runtime, anything that relies on IO or 193 /// timers will not work unless there is another thread currently calling 194 /// [`Runtime::block_on`] on the same runtime. 195 /// 196 /// # If the runtime has been shut down 197 /// 198 /// If the `Handle`'s associated `Runtime` has been shut down (through 199 /// [`Runtime::shutdown_background`], [`Runtime::shutdown_timeout`], or by 200 /// dropping it) and `Handle::block_on` is used it might return an error or 201 /// panic. Specifically IO resources will return an error and timers will 202 /// panic. Runtime independent futures will run as normal. 203 /// 204 /// # Panics 205 /// 206 /// This function panics if the provided future panics, if called within an 207 /// asynchronous execution context, or if a timer future is executed on a 208 /// runtime that has been shut down. 209 /// 210 /// # Examples 211 /// 212 /// ``` 213 /// use tokio::runtime::Runtime; 214 /// 215 /// // Create the runtime 216 /// let rt = Runtime::new().unwrap(); 217 /// 218 /// // Get a handle from this runtime 219 /// let handle = rt.handle(); 220 /// 221 /// // Execute the future, blocking the current thread until completion 222 /// handle.block_on(async { 223 /// println!("hello"); 224 /// }); 225 /// ``` 226 /// 227 /// Or using `Handle::current`: 228 /// 229 /// ``` 230 /// use tokio::runtime::Handle; 231 /// 232 /// #[tokio::main] 233 /// async fn main () { 234 /// let handle = Handle::current(); 235 /// std::thread::spawn(move || { 236 /// // Using Handle::block_on to run async code in the new thread. 237 /// handle.block_on(async { 238 /// println!("hello"); 239 /// }); 240 /// }); 241 /// } 242 /// ``` 243 /// 244 /// [`JoinError`]: struct@crate::task::JoinError 245 /// [`JoinHandle`]: struct@crate::task::JoinHandle 246 /// [`Runtime::block_on`]: fn@crate::runtime::Runtime::block_on 247 /// [`Runtime::shutdown_background`]: fn@crate::runtime::Runtime::shutdown_background 248 /// [`Runtime::shutdown_timeout`]: fn@crate::runtime::Runtime::shutdown_timeout 249 /// [`spawn_blocking`]: crate::task::spawn_blocking 250 /// [`tokio::fs`]: crate::fs 251 /// [`tokio::net`]: crate::net 252 /// [`tokio::time`]: crate::time 253 #[track_caller] block_on<F: Future>(&self, future: F) -> F::Output254 pub fn block_on<F: Future>(&self, future: F) -> F::Output { 255 #[cfg(all(tokio_unstable, feature = "tracing"))] 256 let future = 257 crate::util::trace::task(future, "block_on", None, super::task::Id::next().as_u64()); 258 259 // Enter the runtime context. This sets the current driver handles and 260 // prevents blocking an existing runtime. 261 let mut enter = context::enter_runtime(&self.inner, true); 262 263 // Block on the future 264 enter 265 .blocking 266 .block_on(future) 267 .expect("failed to park thread") 268 } 269 270 #[track_caller] spawn_named<F>(&self, future: F, _name: Option<&str>) -> JoinHandle<F::Output> where F: Future + Send + 'static, F::Output: Send + 'static,271 pub(crate) fn spawn_named<F>(&self, future: F, _name: Option<&str>) -> JoinHandle<F::Output> 272 where 273 F: Future + Send + 'static, 274 F::Output: Send + 'static, 275 { 276 let id = crate::runtime::task::Id::next(); 277 #[cfg(all(tokio_unstable, feature = "tracing"))] 278 let future = crate::util::trace::task(future, "task", _name, id.as_u64()); 279 self.inner.spawn(future, id) 280 } 281 282 /// Returns the flavor of the current `Runtime`. 283 /// 284 /// # Examples 285 /// 286 /// ``` 287 /// use tokio::runtime::{Handle, RuntimeFlavor}; 288 /// 289 /// #[tokio::main(flavor = "current_thread")] 290 /// async fn main() { 291 /// assert_eq!(RuntimeFlavor::CurrentThread, Handle::current().runtime_flavor()); 292 /// } 293 /// ``` 294 /// 295 /// ``` 296 /// use tokio::runtime::{Handle, RuntimeFlavor}; 297 /// 298 /// #[tokio::main(flavor = "multi_thread", worker_threads = 4)] 299 /// async fn main() { 300 /// assert_eq!(RuntimeFlavor::MultiThread, Handle::current().runtime_flavor()); 301 /// } 302 /// ``` runtime_flavor(&self) -> RuntimeFlavor303 pub fn runtime_flavor(&self) -> RuntimeFlavor { 304 match self.inner { 305 scheduler::Handle::CurrentThread(_) => RuntimeFlavor::CurrentThread, 306 #[cfg(all(feature = "rt-multi-thread", not(tokio_wasi)))] 307 scheduler::Handle::MultiThread(_) => RuntimeFlavor::MultiThread, 308 } 309 } 310 } 311 312 cfg_metrics! { 313 use crate::runtime::RuntimeMetrics; 314 315 impl Handle { 316 /// Returns a view that lets you get information about how the runtime 317 /// is performing. 318 pub fn metrics(&self) -> RuntimeMetrics { 319 RuntimeMetrics::new(self.clone()) 320 } 321 } 322 } 323 324 /// Error returned by `try_current` when no Runtime has been started 325 #[derive(Debug)] 326 pub struct TryCurrentError { 327 kind: TryCurrentErrorKind, 328 } 329 330 impl TryCurrentError { new_no_context() -> Self331 pub(crate) fn new_no_context() -> Self { 332 Self { 333 kind: TryCurrentErrorKind::NoContext, 334 } 335 } 336 new_thread_local_destroyed() -> Self337 pub(crate) fn new_thread_local_destroyed() -> Self { 338 Self { 339 kind: TryCurrentErrorKind::ThreadLocalDestroyed, 340 } 341 } 342 343 /// Returns true if the call failed because there is currently no runtime in 344 /// the Tokio context. is_missing_context(&self) -> bool345 pub fn is_missing_context(&self) -> bool { 346 matches!(self.kind, TryCurrentErrorKind::NoContext) 347 } 348 349 /// Returns true if the call failed because the Tokio context thread-local 350 /// had been destroyed. This can usually only happen if in the destructor of 351 /// other thread-locals. is_thread_local_destroyed(&self) -> bool352 pub fn is_thread_local_destroyed(&self) -> bool { 353 matches!(self.kind, TryCurrentErrorKind::ThreadLocalDestroyed) 354 } 355 } 356 357 enum TryCurrentErrorKind { 358 NoContext, 359 ThreadLocalDestroyed, 360 } 361 362 impl fmt::Debug for TryCurrentErrorKind { fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result363 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 364 use TryCurrentErrorKind::*; 365 match self { 366 NoContext => f.write_str("NoContext"), 367 ThreadLocalDestroyed => f.write_str("ThreadLocalDestroyed"), 368 } 369 } 370 } 371 372 impl fmt::Display for TryCurrentError { fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result373 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 374 use TryCurrentErrorKind::*; 375 match self.kind { 376 NoContext => f.write_str(CONTEXT_MISSING_ERROR), 377 ThreadLocalDestroyed => f.write_str(THREAD_LOCAL_DESTROYED_ERROR), 378 } 379 } 380 } 381 382 impl error::Error for TryCurrentError {} 383