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