Coverage Report

Created: 2026-02-11 07:08

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/tokio-1.49.0/src/runtime/handle.rs
Line
Count
Source
1
use crate::runtime;
2
use 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.
13
pub struct Handle {
14
    pub(crate) inner: scheduler::Handle,
15
}
16
17
use crate::runtime::task::JoinHandle;
18
use crate::runtime::BOX_FUTURE_THRESHOLD;
19
use crate::util::error::{CONTEXT_MISSING_ERROR, THREAD_LOCAL_DESTROYED_ERROR};
20
use crate::util::trace::SpawnMeta;
21
22
use std::future::Future;
23
use std::marker::PhantomData;
24
use 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"]
34
pub struct EnterGuard<'a> {
35
    _guard: context::SetCurrentGuard,
36
    _handle_lifetime: PhantomData<&'a Handle>,
37
}
38
39
impl 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
612k
    pub fn enter(&self) -> EnterGuard<'_> {
87
        EnterGuard {
88
612k
            _guard: match context::try_set_current(&self.inner) {
89
612k
                Some(guard) => guard,
90
0
                None => panic!("{}", crate::util::error::THREAD_LOCAL_DESTROYED_ERROR),
91
            },
92
612k
            _handle_lifetime: PhantomData,
93
        }
94
612k
    }
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
576k
    pub fn current() -> Self {
145
576k
        Handle {
146
576k
            inner: scheduler::Handle::current(),
147
576k
        }
148
576k
    }
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
0
    pub fn try_current() -> Result<Self, TryCurrentError> {
156
0
        context::with_current(|inner| Handle {
157
0
            inner: inner.clone(),
158
0
        })
159
0
    }
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`.
170
    ///
171
    /// See [module level][mod] documentation for more details.
172
    ///
173
    /// [mod]: index.html
174
    ///
175
    /// # Examples
176
    ///
177
    /// ```
178
    /// # #[cfg(not(target_family = "wasm"))]
179
    /// # {
180
    /// use tokio::runtime::Runtime;
181
    ///
182
    /// # fn dox() {
183
    /// // Create the runtime
184
    /// let rt = Runtime::new().unwrap();
185
    /// // Get a handle from this runtime
186
    /// let handle = rt.handle();
187
    ///
188
    /// // Spawn a future onto the runtime using the handle
189
    /// handle.spawn(async {
190
    ///     println!("now running on a worker thread");
191
    /// });
192
    /// # }
193
    /// # }
194
    /// ```
195
    #[track_caller]
196
0
    pub fn spawn<F>(&self, future: F) -> JoinHandle<F::Output>
197
0
    where
198
0
        F: Future + Send + 'static,
199
0
        F::Output: Send + 'static,
200
    {
201
0
        let fut_size = mem::size_of::<F>();
202
0
        if fut_size > BOX_FUTURE_THRESHOLD {
203
0
            self.spawn_named(Box::pin(future), SpawnMeta::new_unnamed(fut_size))
204
        } else {
205
0
            self.spawn_named(future, SpawnMeta::new_unnamed(fut_size))
206
        }
207
0
    }
208
209
    /// Runs the provided function on an executor dedicated to blocking
210
    /// operations.
211
    ///
212
    /// # Examples
213
    ///
214
    /// ```
215
    /// # #[cfg(not(target_family = "wasm"))]
216
    /// # {
217
    /// use tokio::runtime::Runtime;
218
    ///
219
    /// # fn dox() {
220
    /// // Create the runtime
221
    /// let rt = Runtime::new().unwrap();
222
    /// // Get a handle from this runtime
223
    /// let handle = rt.handle();
224
    ///
225
    /// // Spawn a blocking function onto the runtime using the handle
226
    /// handle.spawn_blocking(|| {
227
    ///     println!("now running on a worker thread");
228
    /// });
229
    /// # }
230
    /// # }
231
    /// ```
232
    #[track_caller]
233
576k
    pub fn spawn_blocking<F, R>(&self, func: F) -> JoinHandle<R>
234
576k
    where
235
576k
        F: FnOnce() -> R + Send + 'static,
236
576k
        R: Send + 'static,
237
    {
238
576k
        self.inner.blocking_spawner().spawn_blocking(self, func)
239
576k
    }
Unexecuted instantiation: <tokio::runtime::handle::Handle>::spawn_blocking::<<tokio::fs::read_dir::ReadDir>::poll_next_entry::{closure#0}, (alloc::collections::vec_deque::VecDeque<core::result::Result<tokio::fs::read_dir::DirEntry, std::io::error::Error>>, std::fs::ReadDir, bool)>
<tokio::runtime::handle::Handle>::spawn_blocking::<<tokio::runtime::scheduler::multi_thread::worker::Launch>::launch::{closure#0}, ()>
Line
Count
Source
233
576k
    pub fn spawn_blocking<F, R>(&self, func: F) -> JoinHandle<R>
234
576k
    where
235
576k
        F: FnOnce() -> R + Send + 'static,
236
576k
        R: Send + 'static,
237
    {
238
576k
        self.inner.blocking_spawner().spawn_blocking(self, func)
239
576k
    }
Unexecuted instantiation: <tokio::runtime::handle::Handle>::spawn_blocking::<<tokio::io::blocking::Blocking<std::io::stdio::Stdin> as tokio::io::async_read::AsyncRead>::poll_read::{closure#0}, (core::result::Result<usize, std::io::error::Error>, tokio::io::blocking::Buf, std::io::stdio::Stdin)>
Unexecuted instantiation: <tokio::runtime::handle::Handle>::spawn_blocking::<<tokio::fs::file::File as tokio::io::async_seek::AsyncSeek>::start_seek::{closure#0}, (tokio::fs::file::Operation, tokio::io::blocking::Buf)>
Unexecuted instantiation: <tokio::runtime::handle::Handle>::spawn_blocking::<<tokio::fs::file::File as tokio::io::async_read::AsyncRead>::poll_read::{closure#0}, (tokio::fs::file::Operation, tokio::io::blocking::Buf)>
Unexecuted instantiation: <tokio::runtime::handle::Handle>::spawn_blocking::<<tokio::io::blocking::Blocking<std::io::stdio::Stderr> as tokio::io::async_write::AsyncWrite>::poll_flush::{closure#0}, (core::result::Result<usize, std::io::error::Error>, tokio::io::blocking::Buf, std::io::stdio::Stderr)>
Unexecuted instantiation: <tokio::runtime::handle::Handle>::spawn_blocking::<<tokio::io::blocking::Blocking<std::io::stdio::Stderr> as tokio::io::async_write::AsyncWrite>::poll_write::{closure#0}, (core::result::Result<usize, std::io::error::Error>, tokio::io::blocking::Buf, std::io::stdio::Stderr)>
Unexecuted instantiation: <tokio::runtime::handle::Handle>::spawn_blocking::<<tokio::io::blocking::Blocking<std::io::stdio::Stdout> as tokio::io::async_write::AsyncWrite>::poll_flush::{closure#0}, (core::result::Result<usize, std::io::error::Error>, tokio::io::blocking::Buf, std::io::stdio::Stdout)>
Unexecuted instantiation: <tokio::runtime::handle::Handle>::spawn_blocking::<<tokio::io::blocking::Blocking<std::io::stdio::Stdout> as tokio::io::async_write::AsyncWrite>::poll_write::{closure#0}, (core::result::Result<usize, std::io::error::Error>, tokio::io::blocking::Buf, std::io::stdio::Stdout)>
Unexecuted instantiation: <tokio::runtime::handle::Handle>::spawn_blocking::<<str as tokio::net::addr::sealed::ToSocketAddrsPriv>::to_socket_addrs::{closure#0}, core::result::Result<alloc::vec::into_iter::IntoIter<core::net::socket_addr::SocketAddr>, std::io::error::Error>>
Unexecuted instantiation: <tokio::runtime::handle::Handle>::spawn_blocking::<<(&str, u16) as tokio::net::addr::sealed::ToSocketAddrsPriv>::to_socket_addrs::{closure#0}, core::result::Result<alloc::vec::into_iter::IntoIter<core::net::socket_addr::SocketAddr>, std::io::error::Error>>
240
241
    /// Runs a future to completion on this `Handle`'s associated `Runtime`.
242
    ///
243
    /// This runs the given future on the current thread, blocking until it is
244
    /// complete, and yielding its resolved result. Any tasks or timers which
245
    /// the future spawns internally will be executed on the runtime.
246
    ///
247
    /// When this is used on a `current_thread` runtime, only the
248
    /// [`Runtime::block_on`] method can drive the IO and timer drivers, but the
249
    /// `Handle::block_on` method cannot drive them. This means that, when using
250
    /// this method on a `current_thread` runtime, anything that relies on IO or
251
    /// timers will not work unless there is another thread currently calling
252
    /// [`Runtime::block_on`] on the same runtime.
253
    ///
254
    /// # If the runtime has been shut down
255
    ///
256
    /// If the `Handle`'s associated `Runtime` has been shut down (through
257
    /// [`Runtime::shutdown_background`], [`Runtime::shutdown_timeout`], or by
258
    /// dropping it) and `Handle::block_on` is used it might return an error or
259
    /// panic. Specifically IO resources will return an error and timers will
260
    /// panic. Runtime independent futures will run as normal.
261
    ///
262
    /// # Panics
263
    ///
264
    /// This function will panic if any of the following conditions are met:
265
    /// - The provided future panics.
266
    /// - It is called from within an asynchronous context, such as inside
267
    ///   [`Runtime::block_on`], `Handle::block_on`, or from a function annotated
268
    ///   with [`tokio::main`].
269
    /// - A timer future is executed on a runtime that has been shut down.
270
    ///
271
    /// # Examples
272
    ///
273
    /// ```
274
    /// # #[cfg(not(target_family = "wasm"))]
275
    /// # {
276
    /// use tokio::runtime::Runtime;
277
    ///
278
    /// // Create the runtime
279
    /// let rt  = Runtime::new().unwrap();
280
    ///
281
    /// // Get a handle from this runtime
282
    /// let handle = rt.handle();
283
    ///
284
    /// // Execute the future, blocking the current thread until completion
285
    /// handle.block_on(async {
286
    ///     println!("hello");
287
    /// });
288
    /// # }
289
    /// ```
290
    ///
291
    /// Or using `Handle::current`:
292
    ///
293
    /// ```
294
    /// # #[cfg(not(target_family = "wasm"))]
295
    /// # {
296
    /// use tokio::runtime::Handle;
297
    ///
298
    /// #[tokio::main]
299
    /// async fn main () {
300
    ///     let handle = Handle::current();
301
    ///     std::thread::spawn(move || {
302
    ///         // Using Handle::block_on to run async code in the new thread.
303
    ///         handle.block_on(async {
304
    ///             println!("hello");
305
    ///         });
306
    ///     });
307
    /// }
308
    /// # }
309
    /// ```
310
    ///
311
    /// `Handle::block_on` may be combined with [`task::block_in_place`] to
312
    /// re-enter the async context of a multi-thread scheduler runtime:
313
    /// ```
314
    /// # #[cfg(not(target_family = "wasm"))]
315
    /// # {
316
    /// use tokio::task;
317
    /// use tokio::runtime::Handle;
318
    ///
319
    /// # async fn docs() {
320
    /// task::block_in_place(move || {
321
    ///     Handle::current().block_on(async move {
322
    ///         // do something async
323
    ///     });
324
    /// });
325
    /// # }
326
    /// # }
327
    /// ```
328
    ///
329
    /// [`JoinError`]: struct@crate::task::JoinError
330
    /// [`JoinHandle`]: struct@crate::task::JoinHandle
331
    /// [`Runtime::block_on`]: fn@crate::runtime::Runtime::block_on
332
    /// [`Runtime::shutdown_background`]: fn@crate::runtime::Runtime::shutdown_background
333
    /// [`Runtime::shutdown_timeout`]: fn@crate::runtime::Runtime::shutdown_timeout
334
    /// [`spawn_blocking`]: crate::task::spawn_blocking
335
    /// [`tokio::fs`]: crate::fs
336
    /// [`tokio::net`]: crate::net
337
    /// [`tokio::time`]: crate::time
338
    /// [`tokio::main`]: ../attr.main.html
339
    /// [`task::block_in_place`]: crate::task::block_in_place
340
    #[track_caller]
341
0
    pub fn block_on<F: Future>(&self, future: F) -> F::Output {
342
0
        let fut_size = mem::size_of::<F>();
343
0
        if fut_size > BOX_FUTURE_THRESHOLD {
344
0
            self.block_on_inner(Box::pin(future), SpawnMeta::new_unnamed(fut_size))
345
        } else {
346
0
            self.block_on_inner(future, SpawnMeta::new_unnamed(fut_size))
347
        }
348
0
    }
349
350
    #[track_caller]
351
0
    fn block_on_inner<F: Future>(&self, future: F, _meta: SpawnMeta<'_>) -> F::Output {
352
        #[cfg(all(
353
            tokio_unstable,
354
            feature = "taskdump",
355
            feature = "rt",
356
            target_os = "linux",
357
            any(target_arch = "aarch64", target_arch = "x86", target_arch = "x86_64")
358
        ))]
359
        let future = super::task::trace::Trace::root(future);
360
361
        #[cfg(all(tokio_unstable, feature = "tracing"))]
362
        let future =
363
            crate::util::trace::task(future, "block_on", _meta, super::task::Id::next().as_u64());
364
365
        // Enter the runtime context. This sets the current driver handles and
366
        // prevents blocking an existing runtime.
367
0
        context::enter_runtime(&self.inner, true, |blocking| {
368
0
            blocking.block_on(future).expect("failed to park thread")
369
0
        })
370
0
    }
371
372
    #[track_caller]
373
0
    pub(crate) fn spawn_named<F>(&self, future: F, meta: SpawnMeta<'_>) -> JoinHandle<F::Output>
374
0
    where
375
0
        F: Future + Send + 'static,
376
0
        F::Output: Send + 'static,
377
    {
378
0
        let id = crate::runtime::task::Id::next();
379
        #[cfg(all(
380
            tokio_unstable,
381
            feature = "taskdump",
382
            feature = "rt",
383
            target_os = "linux",
384
            any(target_arch = "aarch64", target_arch = "x86", target_arch = "x86_64")
385
        ))]
386
        let future = super::task::trace::Trace::root(future);
387
        #[cfg(all(tokio_unstable, feature = "tracing"))]
388
        let future = crate::util::trace::task(future, "task", meta, id.as_u64());
389
0
        self.inner.spawn(future, id, meta.spawned_at)
390
0
    }
391
392
    #[track_caller]
393
    #[allow(dead_code)]
394
    /// # Safety
395
    ///
396
    /// This must only be called in `LocalRuntime` if the runtime has been verified to be owned
397
    /// by the current thread.
398
0
    pub(crate) unsafe fn spawn_local_named<F>(
399
0
        &self,
400
0
        future: F,
401
0
        meta: SpawnMeta<'_>,
402
0
    ) -> JoinHandle<F::Output>
403
0
    where
404
0
        F: Future + 'static,
405
0
        F::Output: 'static,
406
    {
407
0
        let id = crate::runtime::task::Id::next();
408
        #[cfg(all(
409
            tokio_unstable,
410
            feature = "taskdump",
411
            feature = "rt",
412
            target_os = "linux",
413
            any(target_arch = "aarch64", target_arch = "x86", target_arch = "x86_64")
414
        ))]
415
        let future = super::task::trace::Trace::root(future);
416
        #[cfg(all(tokio_unstable, feature = "tracing"))]
417
        let future = crate::util::trace::task(future, "task", meta, id.as_u64());
418
0
        unsafe { self.inner.spawn_local(future, id, meta.spawned_at) }
419
0
    }
420
421
    /// Returns the flavor of the current `Runtime`.
422
    ///
423
    /// # Examples
424
    ///
425
    /// ```
426
    /// use tokio::runtime::{Handle, RuntimeFlavor};
427
    ///
428
    /// #[tokio::main(flavor = "current_thread")]
429
    /// async fn main() {
430
    ///   assert_eq!(RuntimeFlavor::CurrentThread, Handle::current().runtime_flavor());
431
    /// }
432
    /// ```
433
    ///
434
    /// ```
435
    /// # #[cfg(not(target_family = "wasm"))]
436
    /// # {
437
    /// use tokio::runtime::{Handle, RuntimeFlavor};
438
    ///
439
    /// #[tokio::main(flavor = "multi_thread", worker_threads = 4)]
440
    /// async fn main() {
441
    ///   assert_eq!(RuntimeFlavor::MultiThread, Handle::current().runtime_flavor());
442
    /// }
443
    /// # }
444
    /// ```
445
0
    pub fn runtime_flavor(&self) -> RuntimeFlavor {
446
0
        match self.inner {
447
0
            scheduler::Handle::CurrentThread(_) => RuntimeFlavor::CurrentThread,
448
            #[cfg(feature = "rt-multi-thread")]
449
0
            scheduler::Handle::MultiThread(_) => RuntimeFlavor::MultiThread,
450
        }
451
0
    }
452
453
    /// Returns the [`Id`] of the current `Runtime`.
454
    ///
455
    /// # Examples
456
    ///
457
    /// ```
458
    /// use tokio::runtime::Handle;
459
    ///
460
    /// #[tokio::main(flavor = "current_thread")]
461
    /// async fn main() {
462
    ///   println!("Current runtime id: {}", Handle::current().id());
463
    /// }
464
    /// ```
465
    ///
466
    /// [`Id`]: struct@crate::runtime::Id
467
0
    pub fn id(&self) -> runtime::Id {
468
0
        let owned_id = match &self.inner {
469
0
            scheduler::Handle::CurrentThread(handle) => handle.owned_id(),
470
            #[cfg(feature = "rt-multi-thread")]
471
0
            scheduler::Handle::MultiThread(handle) => handle.owned_id(),
472
        };
473
0
        runtime::Id::new(owned_id)
474
0
    }
475
476
    /// Returns a view that lets you get information about how the runtime
477
    /// is performing.
478
0
    pub fn metrics(&self) -> RuntimeMetrics {
479
0
        RuntimeMetrics::new(self.clone())
480
0
    }
481
}
482
483
impl std::panic::UnwindSafe for Handle {}
484
485
impl std::panic::RefUnwindSafe for Handle {}
486
487
cfg_taskdump! {
488
    impl Handle {
489
        /// Captures a snapshot of the runtime's state.
490
        ///
491
        /// If you only want to capture a snapshot of a single future's state, you can use
492
        /// [`Trace::capture`][crate::runtime::dump::Trace].
493
        ///
494
        /// This functionality is experimental, and comes with a number of
495
        /// requirements and limitations.
496
        ///
497
        /// # Examples
498
        ///
499
        /// This can be used to get call traces of each task in the runtime.
500
        /// Calls to `Handle::dump` should usually be enclosed in a
501
        /// [timeout][crate::time::timeout], so that dumping does not escalate a
502
        /// single blocked runtime thread into an entirely blocked runtime.
503
        ///
504
        /// ```
505
        /// # use tokio::runtime::Runtime;
506
        /// # fn dox() {
507
        /// # let rt = Runtime::new().unwrap();
508
        /// # rt.spawn(async {
509
        /// use tokio::runtime::Handle;
510
        /// use tokio::time::{timeout, Duration};
511
        ///
512
        /// // Inside an async block or function.
513
        /// let handle = Handle::current();
514
        /// if let Ok(dump) = timeout(Duration::from_secs(2), handle.dump()).await {
515
        ///     for (i, task) in dump.tasks().iter().enumerate() {
516
        ///         let trace = task.trace();
517
        ///         println!("TASK {i}:");
518
        ///         println!("{trace}\n");
519
        ///     }
520
        /// }
521
        /// # });
522
        /// # }
523
        /// ```
524
        ///
525
        /// This produces highly detailed traces of tasks; e.g.:
526
        ///
527
        /// ```plain
528
        /// TASK 0:
529
        /// ╼ dump::main::{{closure}}::a::{{closure}} at /tokio/examples/dump.rs:18:20
530
        /// └╼ dump::main::{{closure}}::b::{{closure}} at /tokio/examples/dump.rs:23:20
531
        ///    └╼ dump::main::{{closure}}::c::{{closure}} at /tokio/examples/dump.rs:28:24
532
        ///       └╼ tokio::sync::barrier::Barrier::wait::{{closure}} at /tokio/tokio/src/sync/barrier.rs:129:10
533
        ///          └╼ <tokio::util::trace::InstrumentedAsyncOp<F> as core::future::future::Future>::poll at /tokio/tokio/src/util/trace.rs:77:46
534
        ///             └╼ tokio::sync::barrier::Barrier::wait_internal::{{closure}} at /tokio/tokio/src/sync/barrier.rs:183:36
535
        ///                └╼ tokio::sync::watch::Receiver<T>::changed::{{closure}} at /tokio/tokio/src/sync/watch.rs:604:55
536
        ///                   └╼ tokio::sync::watch::changed_impl::{{closure}} at /tokio/tokio/src/sync/watch.rs:755:18
537
        ///                      └╼ <tokio::sync::notify::Notified as core::future::future::Future>::poll at /tokio/tokio/src/sync/notify.rs:1103:9
538
        ///                         └╼ tokio::sync::notify::Notified::poll_notified at /tokio/tokio/src/sync/notify.rs:996:32
539
        /// ```
540
        ///
541
        /// # Requirements
542
        ///
543
        /// ## Debug Info Must Be Available
544
        ///
545
        /// To produce task traces, the application must **not** be compiled
546
        /// with `split debuginfo`. On Linux, including `debuginfo` within the
547
        /// application binary is the (correct) default. You can further ensure
548
        /// this behavior with the following directive in your `Cargo.toml`:
549
        ///
550
        /// ```toml
551
        /// [profile.*]
552
        /// split-debuginfo = "off"
553
        /// ```
554
        ///
555
        /// ## Unstable Features
556
        ///
557
        /// This functionality is **unstable**, and requires both the
558
        /// `--cfg tokio_unstable` and cargo feature `taskdump` to be set.
559
        ///
560
        /// You can do this by setting the `RUSTFLAGS` environment variable
561
        /// before invoking `cargo`; e.g.:
562
        /// ```bash
563
        /// RUSTFLAGS="--cfg tokio_unstable cargo run --example dump
564
        /// ```
565
        ///
566
        /// Or by [configuring][cargo-config] `rustflags` in
567
        /// `.cargo/config.toml`:
568
        /// ```text
569
        /// [build]
570
        /// rustflags = ["--cfg", "tokio_unstable"]
571
        /// ```
572
        ///
573
        /// [cargo-config]:
574
        ///     https://doc.rust-lang.org/cargo/reference/config.html
575
        ///
576
        /// ## Platform Requirements
577
        ///
578
        /// Task dumps are supported on Linux atop `aarch64`, `x86` and `x86_64`.
579
        ///
580
        /// ## Current Thread Runtime Requirements
581
        ///
582
        /// On the `current_thread` runtime, task dumps may only be requested
583
        /// from *within* the context of the runtime being dumped. Do not, for
584
        /// example, await `Handle::dump()` on a different runtime.
585
        ///
586
        /// # Limitations
587
        ///
588
        /// ## Performance
589
        ///
590
        /// Although enabling the `taskdump` feature imposes virtually no
591
        /// additional runtime overhead, actually calling `Handle::dump` is
592
        /// expensive. The runtime must synchronize and pause its workers, then
593
        /// re-poll every task in a special tracing mode. Avoid requesting dumps
594
        /// often.
595
        ///
596
        /// ## Local Executors
597
        ///
598
        /// Tasks managed by local executors (e.g., `FuturesUnordered` and
599
        /// [`LocalSet`][crate::task::LocalSet]) may not appear in task dumps.
600
        ///
601
        /// ## Non-Termination When Workers Are Blocked
602
        ///
603
        /// The future produced by `Handle::dump` may never produce `Ready` if
604
        /// another runtime worker is blocked for more than 250ms. This may
605
        /// occur if a dump is requested during shutdown, or if another runtime
606
        /// worker is infinite looping or synchronously deadlocked. For these
607
        /// reasons, task dumping should usually be paired with an explicit
608
        /// [timeout][crate::time::timeout].
609
        pub async fn dump(&self) -> crate::runtime::Dump {
610
            match &self.inner {
611
                scheduler::Handle::CurrentThread(handle) => handle.dump(),
612
                #[cfg(all(feature = "rt-multi-thread", not(target_os = "wasi")))]
613
                scheduler::Handle::MultiThread(handle) => {
614
                    // perform the trace in a separate thread so that the
615
                    // trace itself does not appear in the taskdump.
616
                    let handle = handle.clone();
617
                    spawn_thread(async {
618
                        let handle = handle;
619
                        handle.dump().await
620
                    }).await
621
                },
622
            }
623
        }
624
625
        /// Produces `true` if the current task is being traced for a dump;
626
        /// otherwise false. This function is only public for integration
627
        /// testing purposes. Do not rely on it.
628
        #[doc(hidden)]
629
        pub fn is_tracing() -> bool {
630
            super::task::trace::Context::is_tracing()
631
        }
632
    }
633
634
    cfg_rt_multi_thread! {
635
        /// Spawn a new thread and asynchronously await on its result.
636
        async fn spawn_thread<F>(f: F) -> <F as Future>::Output
637
        where
638
            F: Future + Send + 'static,
639
            <F as Future>::Output: Send + 'static
640
        {
641
            let (tx, rx) = crate::sync::oneshot::channel();
642
            crate::loom::thread::spawn(|| {
643
                let rt = crate::runtime::Builder::new_current_thread().build().unwrap();
644
                rt.block_on(async {
645
                    let _ = tx.send(f.await);
646
                });
647
            });
648
            rx.await.unwrap()
649
        }
650
    }
651
}
652
653
/// Error returned by `try_current` when no Runtime has been started
654
#[derive(Debug)]
655
pub struct TryCurrentError {
656
    kind: TryCurrentErrorKind,
657
}
658
659
impl TryCurrentError {
660
0
    pub(crate) fn new_no_context() -> Self {
661
0
        Self {
662
0
            kind: TryCurrentErrorKind::NoContext,
663
0
        }
664
0
    }
665
666
0
    pub(crate) fn new_thread_local_destroyed() -> Self {
667
0
        Self {
668
0
            kind: TryCurrentErrorKind::ThreadLocalDestroyed,
669
0
        }
670
0
    }
671
672
    /// Returns true if the call failed because there is currently no runtime in
673
    /// the Tokio context.
674
0
    pub fn is_missing_context(&self) -> bool {
675
0
        matches!(self.kind, TryCurrentErrorKind::NoContext)
676
0
    }
677
678
    /// Returns true if the call failed because the Tokio context thread-local
679
    /// had been destroyed. This can usually only happen if in the destructor of
680
    /// other thread-locals.
681
0
    pub fn is_thread_local_destroyed(&self) -> bool {
682
0
        matches!(self.kind, TryCurrentErrorKind::ThreadLocalDestroyed)
683
0
    }
684
}
685
686
enum TryCurrentErrorKind {
687
    NoContext,
688
    ThreadLocalDestroyed,
689
}
690
691
impl fmt::Debug for TryCurrentErrorKind {
692
0
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
693
0
        match self {
694
0
            TryCurrentErrorKind::NoContext => f.write_str("NoContext"),
695
0
            TryCurrentErrorKind::ThreadLocalDestroyed => f.write_str("ThreadLocalDestroyed"),
696
        }
697
0
    }
698
}
699
700
impl fmt::Display for TryCurrentError {
701
0
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
702
        use TryCurrentErrorKind as E;
703
0
        match self.kind {
704
0
            E::NoContext => f.write_str(CONTEXT_MISSING_ERROR),
705
0
            E::ThreadLocalDestroyed => f.write_str(THREAD_LOCAL_DESTROYED_ERROR),
706
        }
707
0
    }
708
}
709
710
impl error::Error for TryCurrentError {}