Debian Codegraph @

third_party/rust/tokio/src/runtime/handle.rs

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