Debian Codegraph @

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

raw
1 use super::BOX_FUTURE_THRESHOLD;
2 use crate::runtime::blocking::BlockingPool;
3 use crate::runtime::scheduler::CurrentThread;
4 use crate::runtime::{context, EnterGuard, Handle};
5 use crate::task::JoinHandle;
6
7 use std::future::Future;
8 use std::time::Duration;
9
10 cfg_rt_multi_thread! {
11 use crate::runtime::Builder;
12 use crate::runtime::scheduler::MultiThread;
13
14 cfg_unstable! {
15 use crate::runtime::scheduler::MultiThreadAlt;
16 }
17 }
18
19 /// The Tokio runtime.
20 ///
21 /// The runtime provides an I/O driver, task scheduler, [timer], and
22 /// blocking pool, necessary for running asynchronous tasks.
23 ///
24 /// Instances of `Runtime` can be created using [`new`], or [`Builder`].
25 /// However, most users will use the [`#[tokio::main]`][main] annotation on
26 /// their entry point instead.
27 ///
28 /// See [module level][mod] documentation for more details.
29 ///
30 /// # Shutdown
31 ///
32 /// Shutting down the runtime is done by dropping the value, or calling
33 /// [`shutdown_background`] or [`shutdown_timeout`].
34 ///
35 /// Tasks spawned through [`Runtime::spawn`] keep running until they yield.
36 /// Then they are dropped. They are not *guaranteed* to run to completion, but
37 /// *might* do so if they do not yield until completion.
38 ///
39 /// Blocking functions spawned through [`Runtime::spawn_blocking`] keep running
40 /// until they return.
41 ///
42 /// The thread initiating the shutdown blocks until all spawned work has been
43 /// stopped. This can take an indefinite amount of time. The `Drop`
44 /// implementation waits forever for this.
45 ///
46 /// The [`shutdown_background`] and [`shutdown_timeout`] methods can be used if
47 /// waiting forever is undesired. When the timeout is reached, spawned work that
48 /// did not stop in time and threads running it are leaked. The work continues
49 /// to run until one of the stopping conditions is fulfilled, but the thread
50 /// initiating the shutdown is unblocked.
51 ///
52 /// Once the runtime has been dropped, any outstanding I/O resources bound to
53 /// it will no longer function. Calling any method on them will result in an
54 /// error.
55 ///
56 /// # Sharing
57 ///
58 /// There are several ways to establish shared access to a Tokio runtime:
59 ///
60 /// * Using an <code>[Arc]\<Runtime></code>.
61 /// * Using a [`Handle`].
62 /// * Entering the runtime context.
63 ///
64 /// Using an <code>[Arc]\<Runtime></code> or [`Handle`] allows you to do various
65 /// things with the runtime such as spawning new tasks or entering the runtime
66 /// context. Both types can be cloned to create a new handle that allows access
67 /// to the same runtime. By passing clones into different tasks or threads, you
68 /// will be able to access the runtime from those tasks or threads.
69 ///
70 /// The difference between <code>[Arc]\<Runtime></code> and [`Handle`] is that
71 /// an <code>[Arc]\<Runtime></code> will prevent the runtime from shutting down,
72 /// whereas a [`Handle`] does not prevent that. This is because shutdown of the
73 /// runtime happens when the destructor of the `Runtime` object runs.
74 ///
75 /// Calls to [`shutdown_background`] and [`shutdown_timeout`] require exclusive
76 /// ownership of the `Runtime` type. When using an <code>[Arc]\<Runtime></code>,
77 /// this can be achieved via [`Arc::try_unwrap`] when only one strong count
78 /// reference is left over.
79 ///
80 /// The runtime context is entered using the [`Runtime::enter`] or
81 /// [`Handle::enter`] methods, which use a thread-local variable to store the
82 /// current runtime. Whenever you are inside the runtime context, methods such
83 /// as [`tokio::spawn`] will use the runtime whose context you are inside.
84 ///
85 /// [timer]: crate::time
86 /// [mod]: index.html
87 /// [`new`]: method@Self::new
88 /// [`Builder`]: struct@Builder
89 /// [`Handle`]: struct@Handle
90 /// [main]: macro@crate::main
91 /// [`tokio::spawn`]: crate::spawn
92 /// [`Arc::try_unwrap`]: std::sync::Arc::try_unwrap
93 /// [Arc]: std::sync::Arc
94 /// [`shutdown_background`]: method@Runtime::shutdown_background
95 /// [`shutdown_timeout`]: method@Runtime::shutdown_timeout
96 #[derive(Debug)]
97 pub struct Runtime {
98 /// Task scheduler
99 scheduler: Scheduler,
100
101 /// Handle to runtime, also contains driver handles
102 handle: Handle,
103
104 /// Blocking pool handle, used to signal shutdown
105 blocking_pool: BlockingPool,
106 }
107
108 /// The flavor of a `Runtime`.
109 ///
110 /// This is the return type for [`Handle::runtime_flavor`](crate::runtime::Handle::runtime_flavor()).
111 #[derive(Debug, PartialEq, Eq)]
112 #[non_exhaustive]
113 pub enum RuntimeFlavor {
114 /// The flavor that executes all tasks on the current thread.
115 CurrentThread,
116 /// The flavor that executes tasks across multiple threads.
117 MultiThread,
118 /// The flavor that executes tasks across multiple threads.
119 #[cfg(tokio_unstable)]
120 MultiThreadAlt,
121 }
122
123 /// The runtime scheduler is either a multi-thread or a current-thread executor.
124 #[derive(Debug)]
125 pub(super) enum Scheduler {
126 /// Execute all tasks on the current-thread.
127 CurrentThread(CurrentThread),
128
129 /// Execute tasks across multiple threads.
130 #[cfg(feature = "rt-multi-thread")]
131 MultiThread(MultiThread),
132
133 /// Execute tasks across multiple threads.
134 #[cfg(all(tokio_unstable, feature = "rt-multi-thread"))]
135 MultiThreadAlt(MultiThreadAlt),
136 }
137
138 impl Runtime {
139 pub(super) fn from_parts(
140 scheduler: Scheduler,
141 handle: Handle,
142 blocking_pool: BlockingPool,
143 ) -> Runtime {
144 Runtime {
145 scheduler,
146 handle,
147 blocking_pool,
148 }
149 }
150
151 /// Creates a new runtime instance with default configuration values.
152 ///
153 /// This results in the multi threaded scheduler, I/O driver, and time driver being
154 /// initialized.
155 ///
156 /// Most applications will not need to call this function directly. Instead,
157 /// they will use the [`#[tokio::main]` attribute][main]. When a more complex
158 /// configuration is necessary, the [runtime builder] may be used.
159 ///
160 /// See [module level][mod] documentation for more details.
161 ///
162 /// # Examples
163 ///
164 /// Creating a new `Runtime` with default configuration values.
165 ///
166 /// ```
167 /// use tokio::runtime::Runtime;
168 ///
169 /// let rt = Runtime::new()
170 /// .unwrap();
171 ///
172 /// // Use the runtime...
173 /// ```
174 ///
175 /// [mod]: index.html
176 /// [main]: ../attr.main.html
177 /// [threaded scheduler]: index.html#threaded-scheduler
178 /// [runtime builder]: crate::runtime::Builder
179 #[cfg(feature = "rt-multi-thread")]
180 #[cfg_attr(docsrs, doc(cfg(feature = "rt-multi-thread")))]
181 pub fn new() -> std::io::Result<Runtime> {
182 Builder::new_multi_thread().enable_all().build()
183 }
184
185 /// Returns a handle to the runtime's spawner.
186 ///
187 /// The returned handle can be used to spawn tasks that run on this runtime, and can
188 /// be cloned to allow moving the `Handle` to other threads.
189 ///
190 /// Calling [`Handle::block_on`] on a handle to a `current_thread` runtime is error-prone.
191 /// Refer to the documentation of [`Handle::block_on`] for more.
192 ///
193 /// # Examples
194 ///
195 /// ```
196 /// use tokio::runtime::Runtime;
197 ///
198 /// let rt = Runtime::new()
199 /// .unwrap();
200 ///
201 /// let handle = rt.handle();
202 ///
203 /// // Use the handle...
204 /// ```
205 pub fn handle(&self) -> &Handle {
206 &self.handle
207 }
208
209 /// Spawns a future onto the Tokio runtime.
210 ///
211 /// This spawns the given future onto the runtime's executor, usually a
212 /// thread pool. The thread pool is then responsible for polling the future
213 /// until it completes.
214 ///
215 /// The provided future will start running in the background immediately
216 /// when `spawn` is called, even if you don't await the returned
217 /// `JoinHandle`.
218 ///
219 /// See [module level][mod] documentation for more details.
220 ///
221 /// [mod]: index.html
222 ///
223 /// # Examples
224 ///
225 /// ```
226 /// use tokio::runtime::Runtime;
227 ///
228 /// # fn dox() {
229 /// // Create the runtime
230 /// let rt = Runtime::new().unwrap();
231 ///
232 /// // Spawn a future onto the runtime
233 /// rt.spawn(async {
234 /// println!("now running on a worker thread");
235 /// });
236 /// # }
237 /// ```
238 #[track_caller]
239 pub fn spawn<F>(&self, future: F) -> JoinHandle<F::Output>
240 where
241 F: Future + Send + 'static,
242 F::Output: Send + 'static,
243 {
244 if cfg!(debug_assertions) && std::mem::size_of::<F>() > BOX_FUTURE_THRESHOLD {
245 self.handle.spawn_named(Box::pin(future), None)
246 } else {
247 self.handle.spawn_named(future, None)
248 }
249 }
250
251 /// Runs the provided function on an executor dedicated to blocking operations.
252 ///
253 /// # Examples
254 ///
255 /// ```
256 /// use tokio::runtime::Runtime;
257 ///
258 /// # fn dox() {
259 /// // Create the runtime
260 /// let rt = Runtime::new().unwrap();
261 ///
262 /// // Spawn a blocking function onto the runtime
263 /// rt.spawn_blocking(|| {
264 /// println!("now running on a worker thread");
265 /// });
266 /// # }
267 /// ```
268 #[track_caller]
269 pub fn spawn_blocking<F, R>(&self, func: F) -> JoinHandle<R>
270 where
271 F: FnOnce() -> R + Send + 'static,
272 R: Send + 'static,
273 {
274 self.handle.spawn_blocking(func)
275 }
276
277 /// Runs a future to completion on the Tokio runtime. This is the
278 /// runtime's entry point.
279 ///
280 /// This runs the given future on the current thread, blocking until it is
281 /// complete, and yielding its resolved result. Any tasks or timers
282 /// which the future spawns internally will be executed on the runtime.
283 ///
284 /// # Non-worker future
285 ///
286 /// Note that the future required by this function does not run as a
287 /// worker. The expectation is that other tasks are spawned by the future here.
288 /// Awaiting on other futures from the future provided here will not
289 /// perform as fast as those spawned as workers.
290 ///
291 /// # Multi thread scheduler
292 ///
293 /// When the multi thread scheduler is used this will allow futures
294 /// to run within the io driver and timer context of the overall runtime.
295 ///
296 /// Any spawned tasks will continue running after `block_on` returns.
297 ///
298 /// # Current thread scheduler
299 ///
300 /// When the current thread scheduler is enabled `block_on`
301 /// can be called concurrently from multiple threads. The first call
302 /// will take ownership of the io and timer drivers. This means
303 /// other threads which do not own the drivers will hook into that one.
304 /// When the first `block_on` completes, other threads will be able to
305 /// "steal" the driver to allow continued execution of their futures.
306 ///
307 /// Any spawned tasks will be suspended after `block_on` returns. Calling
308 /// `block_on` again will resume previously spawned tasks.
309 ///
310 /// # Panics
311 ///
312 /// This function panics if the provided future panics, or if called within an
313 /// asynchronous execution context.
314 ///
315 /// # Examples
316 ///
317 /// ```no_run
318 /// use tokio::runtime::Runtime;
319 ///
320 /// // Create the runtime
321 /// let rt = Runtime::new().unwrap();
322 ///
323 /// // Execute the future, blocking the current thread until completion
324 /// rt.block_on(async {
325 /// println!("hello");
326 /// });
327 /// ```
328 ///
329 /// [handle]: fn@Handle::block_on
330 #[track_caller]
331 pub fn block_on<F: Future>(&self, future: F) -> F::Output {
332 if cfg!(debug_assertions) && std::mem::size_of::<F>() > BOX_FUTURE_THRESHOLD {
333 self.block_on_inner(Box::pin(future))
334 } else {
335 self.block_on_inner(future)
336 }
337 }
338
339 #[track_caller]
340 fn block_on_inner<F: Future>(&self, future: F) -> F::Output {
341 #[cfg(all(
342 tokio_unstable,
343 tokio_taskdump,
344 feature = "rt",
345 target_os = "linux",
346 any(target_arch = "aarch64", target_arch = "x86", target_arch = "x86_64")
347 ))]
348 let future = super::task::trace::Trace::root(future);
349
350 #[cfg(all(tokio_unstable, feature = "tracing"))]
351 let future = crate::util::trace::task(
352 future,
353 "block_on",
354 None,
355 crate::runtime::task::Id::next().as_u64(),
356 );
357
358 let _enter = self.enter();
359
360 match &self.scheduler {
361 Scheduler::CurrentThread(exec) => exec.block_on(&self.handle.inner, future),
362 #[cfg(feature = "rt-multi-thread")]
363 Scheduler::MultiThread(exec) => exec.block_on(&self.handle.inner, future),
364 #[cfg(all(tokio_unstable, feature = "rt-multi-thread"))]
365 Scheduler::MultiThreadAlt(exec) => exec.block_on(&self.handle.inner, future),
366 }
367 }
368
369 /// Enters the runtime context.
370 ///
371 /// This allows you to construct types that must have an executor
372 /// available on creation such as [`Sleep`] or [`TcpStream`]. It will
373 /// also allow you to call methods such as [`tokio::spawn`].
374 ///
375 /// [`Sleep`]: struct@crate::time::Sleep
376 /// [`TcpStream`]: struct@crate::net::TcpStream
377 /// [`tokio::spawn`]: fn@crate::spawn
378 ///
379 /// # Example
380 ///
381 /// ```
382 /// use tokio::runtime::Runtime;
383 /// use tokio::task::JoinHandle;
384 ///
385 /// fn function_that_spawns(msg: String) -> JoinHandle<()> {
386 /// // Had we not used `rt.enter` below, this would panic.
387 /// tokio::spawn(async move {
388 /// println!("{}", msg);
389 /// })
390 /// }
391 ///
392 /// fn main() {
393 /// let rt = Runtime::new().unwrap();
394 ///
395 /// let s = "Hello World!".to_string();
396 ///
397 /// // By entering the context, we tie `tokio::spawn` to this executor.
398 /// let _guard = rt.enter();
399 /// let handle = function_that_spawns(s);
400 ///
401 /// // Wait for the task before we end the test.
402 /// rt.block_on(handle).unwrap();
403 /// }
404 /// ```
405 pub fn enter(&self) -> EnterGuard<'_> {
406 self.handle.enter()
407 }
408
409 /// Shuts down the runtime, waiting for at most `duration` for all spawned
410 /// work to stop.
411 ///
412 /// See the [struct level documentation](Runtime#shutdown) for more details.
413 ///
414 /// # Examples
415 ///
416 /// ```
417 /// use tokio::runtime::Runtime;
418 /// use tokio::task;
419 ///
420 /// use std::thread;
421 /// use std::time::Duration;
422 ///
423 /// fn main() {
424 /// let runtime = Runtime::new().unwrap();
425 ///
426 /// runtime.block_on(async move {
427 /// task::spawn_blocking(move || {
428 /// thread::sleep(Duration::from_secs(10_000));
429 /// });
430 /// });
431 ///
432 /// runtime.shutdown_timeout(Duration::from_millis(100));
433 /// }
434 /// ```
435 pub fn shutdown_timeout(mut self, duration: Duration) {
436 // Wakeup and shutdown all the worker threads
437 self.handle.inner.shutdown();
438 self.blocking_pool.shutdown(Some(duration));
439 }
440
441 /// Shuts down the runtime, without waiting for any spawned work to stop.
442 ///
443 /// This can be useful if you want to drop a runtime from within another runtime.
444 /// Normally, dropping a runtime will block indefinitely for spawned blocking tasks
445 /// to complete, which would normally not be permitted within an asynchronous context.
446 /// By calling `shutdown_background()`, you can drop the runtime from such a context.
447 ///
448 /// Note however, that because we do not wait for any blocking tasks to complete, this
449 /// may result in a resource leak (in that any blocking tasks are still running until they
450 /// return.
451 ///
452 /// See the [struct level documentation](Runtime#shutdown) for more details.
453 ///
454 /// This function is equivalent to calling `shutdown_timeout(Duration::from_nanos(0))`.
455 ///
456 /// ```
457 /// use tokio::runtime::Runtime;
458 ///
459 /// fn main() {
460 /// let runtime = Runtime::new().unwrap();
461 ///
462 /// runtime.block_on(async move {
463 /// let inner_runtime = Runtime::new().unwrap();
464 /// // ...
465 /// inner_runtime.shutdown_background();
466 /// });
467 /// }
468 /// ```
469 pub fn shutdown_background(self) {
470 self.shutdown_timeout(Duration::from_nanos(0));
471 }
472
473 /// Returns a view that lets you get information about how the runtime
474 /// is performing.
475 pub fn metrics(&self) -> crate::runtime::RuntimeMetrics {
476 self.handle.metrics()
477 }
478 }
479
480 #[allow(clippy::single_match)] // there are comments in the error branch, so we don't want if-let
481 impl Drop for Runtime {
482 fn drop(&mut self) {
483 match &mut self.scheduler {
484 Scheduler::CurrentThread(current_thread) => {
485 // This ensures that tasks spawned on the current-thread
486 // runtime are dropped inside the runtime's context.
487 let _guard = context::try_set_current(&self.handle.inner);
488 current_thread.shutdown(&self.handle.inner);
489 }
490 #[cfg(feature = "rt-multi-thread")]
491 Scheduler::MultiThread(multi_thread) => {
492 // The threaded scheduler drops its tasks on its worker threads, which is
493 // already in the runtime's context.
494 multi_thread.shutdown(&self.handle.inner);
495 }
496 #[cfg(all(tokio_unstable, feature = "rt-multi-thread"))]
497 Scheduler::MultiThreadAlt(multi_thread) => {
498 // The threaded scheduler drops its tasks on its worker threads, which is
499 // already in the runtime's context.
500 multi_thread.shutdown(&self.handle.inner);
501 }
502 }
503 }
504 }
505
506 impl std::panic::UnwindSafe for Runtime {}
507
508 impl std::panic::RefUnwindSafe for Runtime {}