tokio/runtime/handle.rs
1use crate::runtime;
2use crate::runtime::{context, scheduler, RuntimeFlavor, RuntimeMetrics};
3
4/// Handle to the runtime.
5///
6/// The handle is internally reference-counted and can be freely cloned. A handle can be
7/// obtained using the [`Runtime::handle`] method.
8///
9/// [`Runtime::handle`]: crate::runtime::Runtime::handle()
10#[derive(Debug, Clone)]
11// When the `rt` feature is *not* enabled, this type is still defined, but not
12// included in the public API.
13pub struct Handle {
14 pub(crate) inner: scheduler::Handle,
15}
16
17use crate::runtime::task::JoinHandle;
18use crate::runtime::BOX_FUTURE_THRESHOLD;
19use crate::util::error::{CONTEXT_MISSING_ERROR, THREAD_LOCAL_DESTROYED_ERROR};
20use crate::util::trace::SpawnMeta;
21
22use std::future::Future;
23use std::marker::PhantomData;
24use std::{error, fmt, mem};
25
26/// Runtime context guard.
27///
28/// Returned by [`Runtime::enter`] and [`Handle::enter`], the context guard exits
29/// the runtime context on drop.
30///
31/// [`Runtime::enter`]: fn@crate::runtime::Runtime::enter
32#[derive(Debug)]
33#[must_use = "Creating and dropping a guard does nothing"]
34pub struct EnterGuard<'a> {
35 _guard: context::SetCurrentGuard,
36 _handle_lifetime: PhantomData<&'a Handle>,
37}
38
39impl Handle {
40 /// Enters the runtime context. This allows you to construct types that must
41 /// have an executor available on creation such as [`Sleep`] or
42 /// [`TcpStream`]. It will also allow you to call methods such as
43 /// [`tokio::spawn`] and [`Handle::current`] without panicking.
44 ///
45 /// # Panics
46 ///
47 /// When calling `Handle::enter` multiple times, the returned guards
48 /// **must** be dropped in the reverse order that they were acquired.
49 /// Failure to do so will result in a panic and possible memory leaks.
50 ///
51 /// # Examples
52 ///
53 /// ```
54 /// # #[cfg(not(target_family = "wasm"))]
55 /// # {
56 /// use tokio::runtime::Runtime;
57 ///
58 /// let rt = Runtime::new().unwrap();
59 ///
60 /// let _guard = rt.enter();
61 /// tokio::spawn(async {
62 /// println!("Hello world!");
63 /// });
64 /// # }
65 /// ```
66 ///
67 /// Do **not** do the following, this shows a scenario that will result in a
68 /// panic and possible memory leak.
69 ///
70 /// ```should_panic,ignore-wasm
71 /// use tokio::runtime::Runtime;
72 ///
73 /// let rt1 = Runtime::new().unwrap();
74 /// let rt2 = Runtime::new().unwrap();
75 ///
76 /// let enter1 = rt1.enter();
77 /// let enter2 = rt2.enter();
78 ///
79 /// drop(enter1);
80 /// drop(enter2);
81 /// ```
82 ///
83 /// [`Sleep`]: struct@crate::time::Sleep
84 /// [`TcpStream`]: struct@crate::net::TcpStream
85 /// [`tokio::spawn`]: fn@crate::spawn
86 pub fn enter(&self) -> EnterGuard<'_> {
87 EnterGuard {
88 _guard: match context::try_set_current(&self.inner) {
89 Some(guard) => guard,
90 None => panic!("{}", crate::util::error::THREAD_LOCAL_DESTROYED_ERROR),
91 },
92 _handle_lifetime: PhantomData,
93 }
94 }
95
96 /// Returns a `Handle` view over the currently running `Runtime`.
97 ///
98 /// # Panics
99 ///
100 /// This will panic if called outside the context of a Tokio runtime. That means that you must
101 /// call this on one of the threads **being run by the runtime**, or from a thread with an active
102 /// `EnterGuard`. Calling this from within a thread created by `std::thread::spawn` (for example)
103 /// will cause a panic unless that thread has an active `EnterGuard`.
104 ///
105 /// # Examples
106 ///
107 /// This can be used to obtain the handle of the surrounding runtime from an async
108 /// block or function running on that runtime.
109 ///
110 /// ```
111 /// # #[cfg(not(target_family = "wasm"))]
112 /// # {
113 /// # use std::thread;
114 /// # use tokio::runtime::Runtime;
115 /// # fn dox() {
116 /// # let rt = Runtime::new().unwrap();
117 /// # rt.spawn(async {
118 /// use tokio::runtime::Handle;
119 ///
120 /// // Inside an async block or function.
121 /// let handle = Handle::current();
122 /// handle.spawn(async {
123 /// println!("now running in the existing Runtime");
124 /// });
125 ///
126 /// # let handle =
127 /// thread::spawn(move || {
128 /// // Notice that the handle is created outside of this thread and then moved in
129 /// handle.spawn(async { /* ... */ });
130 /// // This next line would cause a panic because we haven't entered the runtime
131 /// // and created an EnterGuard
132 /// // let handle2 = Handle::current(); // panic
133 /// // So we create a guard here with Handle::enter();
134 /// let _guard = handle.enter();
135 /// // Now we can call Handle::current();
136 /// let handle2 = Handle::current();
137 /// });
138 /// # handle.join().unwrap();
139 /// # });
140 /// # }
141 /// # }
142 /// ```
143 #[track_caller]
144 pub fn current() -> Self {
145 Handle {
146 inner: scheduler::Handle::current(),
147 }
148 }
149
150 /// Returns a Handle view over the currently running Runtime
151 ///
152 /// Returns an error if no Runtime has been started
153 ///
154 /// Contrary to `current`, this never panics
155 pub fn try_current() -> Result<Self, TryCurrentError> {
156 context::with_current(|inner| Handle {
157 inner: inner.clone(),
158 })
159 }
160
161 /// Spawns a future onto the Tokio runtime.
162 ///
163 /// This spawns the given future onto the runtime's executor, usually a
164 /// thread pool. The thread pool is then responsible for polling the future
165 /// until it completes.
166 ///
167 /// The provided future will start running in the background immediately
168 /// when `spawn` is called, even if you don't await the returned
169 /// `JoinHandle` (assuming that the runtime [is running][running-runtime]).
170 ///
171 /// See [module level][mod] documentation for more details.
172 ///
173 /// [mod]: index.html
174 /// [running-runtime]: index.html#driving-the-runtime
175 ///
176 /// # Examples
177 ///
178 /// ```
179 /// # #[cfg(not(target_family = "wasm"))]
180 /// # {
181 /// use tokio::runtime::Runtime;
182 ///
183 /// # fn dox() {
184 /// // Create the runtime
185 /// let rt = Runtime::new().unwrap();
186 /// // Get a handle from this runtime
187 /// let handle = rt.handle();
188 ///
189 /// // Spawn a future onto the runtime using the handle
190 /// handle.spawn(async {
191 /// println!("now running on a worker thread");
192 /// });
193 /// # }
194 /// # }
195 /// ```
196 #[track_caller]
197 pub fn spawn<F>(&self, future: F) -> JoinHandle<F::Output>
198 where
199 F: Future + Send + 'static,
200 F::Output: Send + 'static,
201 {
202 let fut_size = mem::size_of::<F>();
203 if fut_size > BOX_FUTURE_THRESHOLD {
204 self.spawn_named(Box::pin(future), SpawnMeta::new_unnamed(fut_size))
205 } else {
206 self.spawn_named(future, SpawnMeta::new_unnamed(fut_size))
207 }
208 }
209
210 /// Runs the provided function on an executor dedicated to blocking
211 /// operations.
212 ///
213 /// # Examples
214 ///
215 /// ```
216 /// # #[cfg(not(target_family = "wasm"))]
217 /// # {
218 /// use tokio::runtime::Runtime;
219 ///
220 /// # fn dox() {
221 /// // Create the runtime
222 /// let rt = Runtime::new().unwrap();
223 /// // Get a handle from this runtime
224 /// let handle = rt.handle();
225 ///
226 /// // Spawn a blocking function onto the runtime using the handle
227 /// handle.spawn_blocking(|| {
228 /// println!("now running on a worker thread");
229 /// });
230 /// # }
231 /// # }
232 /// ```
233 #[track_caller]
234 pub fn spawn_blocking<F, R>(&self, func: F) -> JoinHandle<R>
235 where
236 F: FnOnce() -> R + Send + 'static,
237 R: Send + 'static,
238 {
239 self.inner.blocking_spawner().spawn_blocking(self, func)
240 }
241
242 /// Runs a future to completion on this `Handle`'s associated `Runtime`.
243 ///
244 /// This runs the given future on the current thread, blocking until it is
245 /// complete, and yielding its resolved result. Any tasks or timers which
246 /// the future spawns internally will be executed on the runtime.
247 ///
248 /// When this is used on a `current_thread` runtime, only the
249 /// [`Runtime::block_on`] method can drive the IO and timer drivers, but the
250 /// `Handle::block_on` method cannot drive them. This means that, when using
251 /// this method on a `current_thread` runtime, anything that relies on IO or
252 /// timers will not work unless there is another thread currently calling
253 /// [`Runtime::block_on`] on the same runtime.
254 ///
255 /// # If the runtime has been shut down
256 ///
257 /// If the `Handle`'s associated `Runtime` has been shut down (through
258 /// [`Runtime::shutdown_background`], [`Runtime::shutdown_timeout`], or by
259 /// dropping it) and `Handle::block_on` is used it might return an error or
260 /// panic. Specifically IO resources will return an error and timers will
261 /// panic. Runtime independent futures will run as normal.
262 ///
263 /// # Panics
264 ///
265 /// This function will panic if any of the following conditions are met:
266 /// - The provided future panics.
267 /// - It is called from within an asynchronous context, such as inside
268 /// [`Runtime::block_on`], `Handle::block_on`, or from a function annotated
269 /// with [`tokio::main`].
270 /// - A timer future is executed on a runtime that has been shut down.
271 ///
272 /// # Examples
273 ///
274 /// ```
275 /// # #[cfg(not(target_family = "wasm"))]
276 /// # {
277 /// use tokio::runtime::Runtime;
278 ///
279 /// // Create the runtime
280 /// let rt = Runtime::new().unwrap();
281 ///
282 /// // Get a handle from this runtime
283 /// let handle = rt.handle();
284 ///
285 /// // Execute the future, blocking the current thread until completion
286 /// handle.block_on(async {
287 /// println!("hello");
288 /// });
289 /// # }
290 /// ```
291 ///
292 /// Or using `Handle::current`:
293 ///
294 /// ```
295 /// # #[cfg(not(target_family = "wasm"))]
296 /// # {
297 /// use tokio::runtime::Handle;
298 ///
299 /// #[tokio::main]
300 /// async fn main () {
301 /// let handle = Handle::current();
302 /// std::thread::spawn(move || {
303 /// // Using Handle::block_on to run async code in the new thread.
304 /// handle.block_on(async {
305 /// println!("hello");
306 /// });
307 /// });
308 /// }
309 /// # }
310 /// ```
311 ///
312 /// `Handle::block_on` may be combined with [`task::block_in_place`] to
313 /// re-enter the async context of a multi-thread scheduler runtime:
314 /// ```
315 /// # #[cfg(not(target_family = "wasm"))]
316 /// # {
317 /// use tokio::task;
318 /// use tokio::runtime::Handle;
319 ///
320 /// # async fn docs() {
321 /// task::block_in_place(move || {
322 /// Handle::current().block_on(async move {
323 /// // do something async
324 /// });
325 /// });
326 /// # }
327 /// # }
328 /// ```
329 ///
330 /// [`JoinError`]: struct@crate::task::JoinError
331 /// [`JoinHandle`]: struct@crate::task::JoinHandle
332 /// [`Runtime::block_on`]: fn@crate::runtime::Runtime::block_on
333 /// [`Runtime::shutdown_background`]: fn@crate::runtime::Runtime::shutdown_background
334 /// [`Runtime::shutdown_timeout`]: fn@crate::runtime::Runtime::shutdown_timeout
335 /// [`spawn_blocking`]: crate::task::spawn_blocking
336 /// [`tokio::fs`]: crate::fs
337 /// [`tokio::net`]: crate::net
338 /// [`tokio::time`]: crate::time
339 /// [`tokio::main`]: ../attr.main.html
340 /// [`task::block_in_place`]: crate::task::block_in_place
341 #[track_caller]
342 pub fn block_on<F: Future>(&self, future: F) -> F::Output {
343 let fut_size = mem::size_of::<F>();
344 if fut_size > BOX_FUTURE_THRESHOLD {
345 self.block_on_inner(Box::pin(future), SpawnMeta::new_unnamed(fut_size))
346 } else {
347 self.block_on_inner(future, SpawnMeta::new_unnamed(fut_size))
348 }
349 }
350
351 #[track_caller]
352 fn block_on_inner<F: Future>(&self, future: F, _meta: SpawnMeta<'_>) -> F::Output {
353 #[cfg(all(
354 tokio_unstable,
355 feature = "taskdump",
356 feature = "rt",
357 target_os = "linux",
358 any(
359 target_arch = "aarch64",
360 target_arch = "x86",
361 target_arch = "x86_64",
362 target_arch = "s390x"
363 )
364 ))]
365 let future = super::task::trace::Trace::root(future);
366
367 #[cfg(all(tokio_unstable, feature = "tracing"))]
368 let future =
369 crate::util::trace::task(future, "block_on", _meta, super::task::Id::next().as_u64());
370
371 // Enter the runtime context. This sets the current driver handles and
372 // prevents blocking an existing runtime.
373 context::enter_runtime(&self.inner, true, |blocking| {
374 blocking.block_on(future).expect("failed to park thread")
375 })
376 }
377
378 #[track_caller]
379 pub(crate) fn spawn_named<F>(&self, future: F, meta: SpawnMeta<'_>) -> JoinHandle<F::Output>
380 where
381 F: Future + Send + 'static,
382 F::Output: Send + 'static,
383 {
384 let id = crate::runtime::task::Id::next();
385 #[cfg(all(
386 tokio_unstable,
387 feature = "taskdump",
388 feature = "rt",
389 target_os = "linux",
390 any(
391 target_arch = "aarch64",
392 target_arch = "x86",
393 target_arch = "x86_64",
394 target_arch = "s390x"
395 )
396 ))]
397 let future = super::task::trace::Trace::root(future);
398 #[cfg(all(tokio_unstable, feature = "tracing"))]
399 let future = crate::util::trace::task(future, "task", meta, id.as_u64());
400 self.inner.spawn(future, id, meta.spawned_at)
401 }
402
403 #[track_caller]
404 #[allow(dead_code)]
405 /// # Safety
406 ///
407 /// This must only be called in `LocalRuntime` if the runtime has been verified to be owned
408 /// by the current thread.
409 pub(crate) unsafe fn spawn_local_named<F>(
410 &self,
411 future: F,
412 meta: SpawnMeta<'_>,
413 ) -> JoinHandle<F::Output>
414 where
415 F: Future + 'static,
416 F::Output: 'static,
417 {
418 let id = crate::runtime::task::Id::next();
419 #[cfg(all(
420 tokio_unstable,
421 feature = "taskdump",
422 feature = "rt",
423 target_os = "linux",
424 any(
425 target_arch = "aarch64",
426 target_arch = "x86",
427 target_arch = "x86_64",
428 target_arch = "s390x"
429 )
430 ))]
431 let future = super::task::trace::Trace::root(future);
432 #[cfg(all(tokio_unstable, feature = "tracing"))]
433 let future = crate::util::trace::task(future, "task", meta, id.as_u64());
434 unsafe { self.inner.spawn_local(future, id, meta.spawned_at) }
435 }
436
437 /// Returns the flavor of the current `Runtime`.
438 ///
439 /// # Examples
440 ///
441 /// ```
442 /// use tokio::runtime::{Handle, RuntimeFlavor};
443 ///
444 /// #[tokio::main(flavor = "current_thread")]
445 /// async fn main() {
446 /// assert_eq!(RuntimeFlavor::CurrentThread, Handle::current().runtime_flavor());
447 /// }
448 /// ```
449 ///
450 /// ```
451 /// # #[cfg(not(target_family = "wasm"))]
452 /// # {
453 /// use tokio::runtime::{Handle, RuntimeFlavor};
454 ///
455 /// #[tokio::main(flavor = "multi_thread", worker_threads = 4)]
456 /// async fn main() {
457 /// assert_eq!(RuntimeFlavor::MultiThread, Handle::current().runtime_flavor());
458 /// }
459 /// # }
460 /// ```
461 pub fn runtime_flavor(&self) -> RuntimeFlavor {
462 match self.inner {
463 scheduler::Handle::CurrentThread(_) => RuntimeFlavor::CurrentThread,
464 #[cfg(feature = "rt-multi-thread")]
465 scheduler::Handle::MultiThread(_) => RuntimeFlavor::MultiThread,
466 }
467 }
468
469 /// Returns the [`Id`] of the current `Runtime`.
470 ///
471 /// # Examples
472 ///
473 /// ```
474 /// use tokio::runtime::Handle;
475 ///
476 /// #[tokio::main(flavor = "current_thread")]
477 /// async fn main() {
478 /// println!("Current runtime id: {}", Handle::current().id());
479 /// }
480 /// ```
481 ///
482 /// [`Id`]: struct@crate::runtime::Id
483 pub fn id(&self) -> runtime::Id {
484 let owned_id = match &self.inner {
485 scheduler::Handle::CurrentThread(handle) => handle.owned_id(),
486 #[cfg(feature = "rt-multi-thread")]
487 scheduler::Handle::MultiThread(handle) => handle.owned_id(),
488 };
489 runtime::Id::new(owned_id)
490 }
491
492 /// Returns the name of the current `Runtime`.
493 ///
494 /// # Examples
495 ///
496 /// ```
497 /// use tokio::runtime::Handle;
498 ///
499 /// #[tokio::main(flavor = "current_thread", name = "my-runtime")]
500 /// async fn main() {
501 /// println!("Current runtime name: {}", Handle::current().name().unwrap());
502 /// }
503 /// ```
504 ///
505 pub fn name(&self) -> Option<&str> {
506 match &self.inner {
507 scheduler::Handle::CurrentThread(handle) => handle.name(),
508 #[cfg(feature = "rt-multi-thread")]
509 scheduler::Handle::MultiThread(handle) => handle.name(),
510 }
511 }
512
513 /// Returns a view that lets you get information about how the runtime
514 /// is performing.
515 pub fn metrics(&self) -> RuntimeMetrics {
516 RuntimeMetrics::new(self.clone())
517 }
518}
519
520impl std::panic::UnwindSafe for Handle {}
521
522impl std::panic::RefUnwindSafe for Handle {}
523
524cfg_taskdump! {
525 impl Handle {
526 /// Captures a snapshot of the runtime's state.
527 ///
528 /// If you only want to capture a snapshot of a single future's state, you can use
529 /// [`Trace::capture`][crate::runtime::dump::Trace].
530 ///
531 /// This functionality is experimental, and comes with a number of
532 /// requirements and limitations.
533 ///
534 /// # Examples
535 ///
536 /// This can be used to get call traces of each task in the runtime.
537 /// Calls to `Handle::dump` should usually be enclosed in a
538 /// [timeout][crate::time::timeout], so that dumping does not escalate a
539 /// single blocked runtime thread into an entirely blocked runtime.
540 ///
541 /// ```
542 /// # use tokio::runtime::Runtime;
543 /// # fn dox() {
544 /// # let rt = Runtime::new().unwrap();
545 /// # rt.spawn(async {
546 /// use tokio::runtime::Handle;
547 /// use tokio::time::{timeout, Duration};
548 ///
549 /// // Inside an async block or function.
550 /// let handle = Handle::current();
551 /// if let Ok(dump) = timeout(Duration::from_secs(2), handle.dump()).await {
552 /// for (i, task) in dump.tasks().iter().enumerate() {
553 /// let trace = task.trace();
554 /// println!("TASK {i}:");
555 /// println!("{trace}\n");
556 /// }
557 /// }
558 /// # });
559 /// # }
560 /// ```
561 ///
562 /// This produces highly detailed traces of tasks; e.g.:
563 ///
564 /// ```plain
565 /// TASK 0:
566 /// ╼ dump::main::{{closure}}::a::{{closure}} at /tokio/examples/dump.rs:18:20
567 /// └╼ dump::main::{{closure}}::b::{{closure}} at /tokio/examples/dump.rs:23:20
568 /// └╼ dump::main::{{closure}}::c::{{closure}} at /tokio/examples/dump.rs:28:24
569 /// └╼ tokio::sync::barrier::Barrier::wait::{{closure}} at /tokio/tokio/src/sync/barrier.rs:129:10
570 /// └╼ <tokio::util::trace::InstrumentedAsyncOp<F> as core::future::future::Future>::poll at /tokio/tokio/src/util/trace.rs:77:46
571 /// └╼ tokio::sync::barrier::Barrier::wait_internal::{{closure}} at /tokio/tokio/src/sync/barrier.rs:183:36
572 /// └╼ tokio::sync::watch::Receiver<T>::changed::{{closure}} at /tokio/tokio/src/sync/watch.rs:604:55
573 /// └╼ tokio::sync::watch::changed_impl::{{closure}} at /tokio/tokio/src/sync/watch.rs:755:18
574 /// └╼ <tokio::sync::notify::Notified as core::future::future::Future>::poll at /tokio/tokio/src/sync/notify.rs:1103:9
575 /// └╼ tokio::sync::notify::Notified::poll_notified at /tokio/tokio/src/sync/notify.rs:996:32
576 /// ```
577 ///
578 /// # Requirements
579 ///
580 /// ## Debug Info Must Be Available
581 ///
582 /// To produce task traces, the application must **not** be compiled
583 /// with `split debuginfo`. On Linux, including `debuginfo` within the
584 /// application binary is the (correct) default. You can further ensure
585 /// this behavior with the following directive in your `Cargo.toml`:
586 ///
587 /// ```toml
588 /// [profile.*]
589 /// split-debuginfo = "off"
590 /// ```
591 ///
592 /// ## Unstable Features
593 ///
594 /// This functionality is **unstable**, and requires both the
595 /// `--cfg tokio_unstable` and cargo feature `taskdump` to be set.
596 ///
597 /// You can do this by setting the `RUSTFLAGS` environment variable
598 /// before invoking `cargo`; e.g.:
599 /// ```bash
600 /// RUSTFLAGS="--cfg tokio_unstable" cargo run --example dump
601 /// ```
602 ///
603 /// Or by [configuring][cargo-config] `rustflags` in
604 /// `.cargo/config.toml`:
605 /// ```text
606 /// [build]
607 /// rustflags = ["--cfg", "tokio_unstable"]
608 /// ```
609 ///
610 /// [cargo-config]:
611 /// https://doc.rust-lang.org/cargo/reference/config.html
612 ///
613 /// ## Platform Requirements
614 ///
615 /// Task dumps are supported on Linux atop `aarch64`, `x86`, `x86_64` and `s390x`.
616 ///
617 /// ## Current Thread Runtime Requirements
618 ///
619 /// On the `current_thread` runtime, task dumps may only be requested
620 /// from *within* the context of the runtime being dumped. Do not, for
621 /// example, await `Handle::dump()` on a different runtime.
622 ///
623 /// # Limitations
624 ///
625 /// ## Performance
626 ///
627 /// Although enabling the `taskdump` feature imposes virtually no
628 /// additional runtime overhead, actually calling `Handle::dump` is
629 /// expensive. The runtime must synchronize and pause its workers, then
630 /// re-poll every task in a special tracing mode. Avoid requesting dumps
631 /// often.
632 ///
633 /// ## Local Executors
634 ///
635 /// Tasks managed by local executors (e.g., `FuturesUnordered` and
636 /// [`LocalSet`][crate::task::LocalSet]) may not appear in task dumps.
637 ///
638 /// ## Non-Termination When Workers Are Blocked
639 ///
640 /// The future produced by `Handle::dump` may never produce `Ready` if
641 /// another runtime worker is blocked for more than 250ms. This may
642 /// occur if a dump is requested during shutdown, or if another runtime
643 /// worker is infinite looping or synchronously deadlocked. For these
644 /// reasons, task dumping should usually be paired with an explicit
645 /// [timeout][crate::time::timeout].
646 pub async fn dump(&self) -> crate::runtime::Dump {
647 match &self.inner {
648 scheduler::Handle::CurrentThread(handle) => handle.dump(),
649 #[cfg(all(feature = "rt-multi-thread", not(target_os = "wasi")))]
650 scheduler::Handle::MultiThread(handle) => {
651 // perform the trace in a separate thread so that the
652 // trace itself does not appear in the taskdump.
653 let handle = handle.clone();
654 spawn_thread(async {
655 let handle = handle;
656 handle.dump().await
657 }).await
658 },
659 }
660 }
661
662 /// Produces `true` if the current task is being traced for a dump;
663 /// otherwise false. This function is only public for integration
664 /// testing purposes. Do not rely on it.
665 #[doc(hidden)]
666 pub fn is_tracing() -> bool {
667 super::task::trace::Context::is_tracing()
668 }
669 }
670
671 cfg_rt_multi_thread! {
672 /// Spawn a new thread and asynchronously await on its result.
673 async fn spawn_thread<F>(f: F) -> <F as Future>::Output
674 where
675 F: Future + Send + 'static,
676 <F as Future>::Output: Send + 'static
677 {
678 let (tx, rx) = crate::sync::oneshot::channel();
679 crate::loom::thread::spawn(|| {
680 let rt = crate::runtime::Builder::new_current_thread().build().unwrap();
681 rt.block_on(async {
682 let _ = tx.send(f.await);
683 });
684 });
685 rx.await.unwrap()
686 }
687 }
688}
689
690/// Error returned by `try_current` when no Runtime has been started
691#[derive(Debug)]
692pub struct TryCurrentError {
693 kind: TryCurrentErrorKind,
694}
695
696impl TryCurrentError {
697 pub(crate) fn new_no_context() -> Self {
698 Self {
699 kind: TryCurrentErrorKind::NoContext,
700 }
701 }
702
703 pub(crate) fn new_thread_local_destroyed() -> Self {
704 Self {
705 kind: TryCurrentErrorKind::ThreadLocalDestroyed,
706 }
707 }
708
709 /// Returns true if the call failed because there is currently no runtime in
710 /// the Tokio context.
711 pub fn is_missing_context(&self) -> bool {
712 matches!(self.kind, TryCurrentErrorKind::NoContext)
713 }
714
715 /// Returns true if the call failed because the Tokio context thread-local
716 /// had been destroyed. This can usually only happen if in the destructor of
717 /// other thread-locals.
718 pub fn is_thread_local_destroyed(&self) -> bool {
719 matches!(self.kind, TryCurrentErrorKind::ThreadLocalDestroyed)
720 }
721}
722
723enum TryCurrentErrorKind {
724 NoContext,
725 ThreadLocalDestroyed,
726}
727
728impl fmt::Debug for TryCurrentErrorKind {
729 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
730 match self {
731 TryCurrentErrorKind::NoContext => f.write_str("NoContext"),
732 TryCurrentErrorKind::ThreadLocalDestroyed => f.write_str("ThreadLocalDestroyed"),
733 }
734 }
735}
736
737impl fmt::Display for TryCurrentError {
738 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
739 use TryCurrentErrorKind as E;
740 match self.kind {
741 E::NoContext => f.write_str(CONTEXT_MISSING_ERROR),
742 E::ThreadLocalDestroyed => f.write_str(THREAD_LOCAL_DESTROYED_ERROR),
743 }
744 }
745}
746
747impl error::Error for TryCurrentError {}