tokio/
lib.rs

1#![allow(
2    clippy::cognitive_complexity,
3    clippy::large_enum_variant,
4    clippy::needless_doctest_main
5)]
6#![warn(
7    missing_debug_implementations,
8    missing_docs,
9    rust_2018_idioms,
10    unreachable_pub
11)]
12#![deny(unused_must_use)]
13#![doc(test(
14    no_crate_inject,
15    attr(deny(warnings, rust_2018_idioms), allow(dead_code, unused_variables))
16))]
17#![cfg_attr(docsrs, feature(doc_cfg))]
18#![cfg_attr(docsrs, allow(unused_attributes))]
19#![cfg_attr(loom, allow(dead_code, unreachable_pub))]
20
21//! A runtime for writing reliable network applications without compromising speed.
22//!
23//! Tokio is an event-driven, non-blocking I/O platform for writing asynchronous
24//! applications with the Rust programming language. At a high level, it
25//! provides a few major components:
26//!
27//! * Tools for [working with asynchronous tasks][tasks], including
28//!   [synchronization primitives and channels][sync] and [timeouts, sleeps, and
29//!   intervals][time].
30//! * APIs for [performing asynchronous I/O][io], including [TCP and UDP][net] sockets,
31//!   [filesystem][fs] operations, and [process] and [signal] management.
32//! * A [runtime] for executing asynchronous code, including a task scheduler,
33//!   an I/O driver backed by the operating system's event queue (epoll, kqueue,
34//!   IOCP, etc...), and a high performance timer.
35//!
36//! Guide level documentation is found on the [website].
37//!
38//! [tasks]: #working-with-tasks
39//! [sync]: crate::sync
40//! [time]: crate::time
41//! [io]: #asynchronous-io
42//! [net]: crate::net
43//! [fs]: crate::fs
44//! [process]: crate::process
45//! [signal]: crate::signal
46//! [fs]: crate::fs
47//! [runtime]: crate::runtime
48//! [website]: https://tokio.rs/tokio/tutorial
49//!
50//! # A Tour of Tokio
51//!
52//! Tokio consists of a number of modules that provide a range of functionality
53//! essential for implementing asynchronous applications in Rust. In this
54//! section, we will take a brief tour of Tokio, summarizing the major APIs and
55//! their uses.
56//!
57//! The easiest way to get started is to enable all features. Do this by
58//! enabling the `full` feature flag:
59//!
60//! ```toml
61//! tokio = { version = "1", features = ["full"] }
62//! ```
63//!
64//! ### Authoring applications
65//!
66//! Tokio is great for writing applications and most users in this case shouldn't
67//! worry too much about what features they should pick. If you're unsure, we suggest
68//! going with `full` to ensure that you don't run into any road blocks while you're
69//! building your application.
70//!
71//! #### Example
72//!
73//! This example shows the quickest way to get started with Tokio.
74//!
75//! ```toml
76//! tokio = { version = "1", features = ["full"] }
77//! ```
78//!
79//! ### Authoring libraries
80//!
81//! As a library author your goal should be to provide the lightest weight crate
82//! that is based on Tokio. To achieve this you should ensure that you only enable
83//! the features you need. This allows users to pick up your crate without having
84//! to enable unnecessary features.
85//!
86//! #### Example
87//!
88//! This example shows how you may want to import features for a library that just
89//! needs to `tokio::spawn` and use a `TcpStream`.
90//!
91//! ```toml
92//! tokio = { version = "1", features = ["rt", "net"] }
93//! ```
94//!
95//! ## Working With Tasks
96//!
97//! Asynchronous programs in Rust are based around lightweight, non-blocking
98//! units of execution called [_tasks_][tasks]. The [`tokio::task`] module provides
99//! important tools for working with tasks:
100//!
101//! * The [`spawn`] function and [`JoinHandle`] type, for scheduling a new task
102//!   on the Tokio runtime and awaiting the output of a spawned task, respectively,
103//! * Functions for [running blocking operations][blocking] in an asynchronous
104//!   task context.
105//!
106//! The [`tokio::task`] module is present only when the "rt" feature flag
107//! is enabled.
108//!
109//! [tasks]: task/index.html#what-are-tasks
110//! [`tokio::task`]: crate::task
111//! [`spawn`]: crate::task::spawn()
112//! [`JoinHandle`]: crate::task::JoinHandle
113//! [blocking]: task/index.html#blocking-and-yielding
114//!
115//! The [`tokio::sync`] module contains synchronization primitives to use when
116//! needing to communicate or share data. These include:
117//!
118//! * channels ([`oneshot`], [`mpsc`], [`watch`], and [`broadcast`]), for sending values
119//!   between tasks,
120//! * a non-blocking [`Mutex`], for controlling access to a shared, mutable
121//!   value,
122//! * an asynchronous [`Barrier`] type, for multiple tasks to synchronize before
123//!   beginning a computation.
124//!
125//! The `tokio::sync` module is present only when the "sync" feature flag is
126//! enabled.
127//!
128//! [`tokio::sync`]: crate::sync
129//! [`Mutex`]: crate::sync::Mutex
130//! [`Barrier`]: crate::sync::Barrier
131//! [`oneshot`]: crate::sync::oneshot
132//! [`mpsc`]: crate::sync::mpsc
133//! [`watch`]: crate::sync::watch
134//! [`broadcast`]: crate::sync::broadcast
135//!
136//! The [`tokio::time`] module provides utilities for tracking time and
137//! scheduling work. This includes functions for setting [timeouts][timeout] for
138//! tasks, [sleeping][sleep] work to run in the future, or [repeating an operation at an
139//! interval][interval].
140//!
141//! In order to use `tokio::time`, the "time" feature flag must be enabled.
142//!
143//! [`tokio::time`]: crate::time
144//! [sleep]: crate::time::sleep()
145//! [interval]: crate::time::interval()
146//! [timeout]: crate::time::timeout()
147//!
148//! Finally, Tokio provides a _runtime_ for executing asynchronous tasks. Most
149//! applications can use the [`#[tokio::main]`][main] macro to run their code on the
150//! Tokio runtime. However, this macro provides only basic configuration options. As
151//! an alternative, the [`tokio::runtime`] module provides more powerful APIs for configuring
152//! and managing runtimes. You should use that module if the `#[tokio::main]` macro doesn't
153//! provide the functionality you need.
154//!
155//! Using the runtime requires the "rt" or "rt-multi-thread" feature flags, to
156//! enable the current-thread [single-threaded scheduler][rt] and the [multi-thread
157//! scheduler][rt-multi-thread], respectively. See the [`runtime` module
158//! documentation][rt-features] for details. In addition, the "macros" feature
159//! flag enables the `#[tokio::main]` and `#[tokio::test]` attributes.
160//!
161//! [main]: attr.main.html
162//! [`tokio::runtime`]: crate::runtime
163//! [`Builder`]: crate::runtime::Builder
164//! [`Runtime`]: crate::runtime::Runtime
165//! [rt]: runtime/index.html#current-thread-scheduler
166//! [rt-multi-thread]: runtime/index.html#multi-thread-scheduler
167//! [rt-features]: runtime/index.html#runtime-scheduler
168//!
169//! ## CPU-bound tasks and blocking code
170//!
171//! Tokio is able to concurrently run many tasks on a few threads by repeatedly
172//! swapping the currently running task on each thread. However, this kind of
173//! swapping can only happen at `.await` points, so code that spends a long time
174//! without reaching an `.await` will prevent other tasks from running. To
175//! combat this, Tokio provides two kinds of threads: Core threads and blocking
176//! threads. The core threads are where all asynchronous code runs, and Tokio
177//! will by default spawn one for each CPU core. The blocking threads are
178//! spawned on demand, can be used to run blocking code that would otherwise
179//! block other tasks from running and are kept alive when not used for a certain
180//! amount of time which can be configured with [`thread_keep_alive`].
181//! Since it is not possible for Tokio to swap out blocking tasks, like it
182//! can do with asynchronous code, the upper limit on the number of blocking
183//! threads is very large. These limits can be configured on the [`Builder`].
184//!
185//! To spawn a blocking task, you should use the [`spawn_blocking`] function.
186//!
187//! [`Builder`]: crate::runtime::Builder
188//! [`spawn_blocking`]: crate::task::spawn_blocking()
189//! [`thread_keep_alive`]: crate::runtime::Builder::thread_keep_alive()
190//!
191//! ```
192//! #[tokio::main]
193//! async fn main() {
194//!     // This is running on a core thread.
195//!
196//!     let blocking_task = tokio::task::spawn_blocking(|| {
197//!         // This is running on a blocking thread.
198//!         // Blocking here is ok.
199//!     });
200//!
201//!     // We can wait for the blocking task like this:
202//!     // If the blocking task panics, the unwrap below will propagate the
203//!     // panic.
204//!     blocking_task.await.unwrap();
205//! }
206//! ```
207//!
208//! If your code is CPU-bound and you wish to limit the number of threads used
209//! to run it, you should use a separate thread pool dedicated to CPU bound tasks.
210//! For example, you could consider using the [rayon] library for CPU-bound
211//! tasks. It is also possible to create an extra Tokio runtime dedicated to
212//! CPU-bound tasks, but if you do this, you should be careful that the extra
213//! runtime runs _only_ CPU-bound tasks, as IO-bound tasks on that runtime
214//! will behave poorly.
215//!
216//! Hint: If using rayon, you can use a [`oneshot`] channel to send the result back
217//! to Tokio when the rayon task finishes.
218//!
219//! [rayon]: https://docs.rs/rayon
220//! [`oneshot`]: crate::sync::oneshot
221//!
222//! ## Asynchronous IO
223//!
224//! As well as scheduling and running tasks, Tokio provides everything you need
225//! to perform input and output asynchronously.
226//!
227//! The [`tokio::io`] module provides Tokio's asynchronous core I/O primitives,
228//! the [`AsyncRead`], [`AsyncWrite`], and [`AsyncBufRead`] traits. In addition,
229//! when the "io-util" feature flag is enabled, it also provides combinators and
230//! functions for working with these traits, forming as an asynchronous
231//! counterpart to [`std::io`].
232//!
233//! Tokio also includes APIs for performing various kinds of I/O and interacting
234//! with the operating system asynchronously. These include:
235//!
236//! * [`tokio::net`], which contains non-blocking versions of [TCP], [UDP], and
237//!   [Unix Domain Sockets][UDS] (enabled by the "net" feature flag),
238//! * [`tokio::fs`], similar to [`std::fs`] but for performing filesystem I/O
239//!   asynchronously (enabled by the "fs" feature flag),
240//! * [`tokio::signal`], for asynchronously handling Unix and Windows OS signals
241//!   (enabled by the "signal" feature flag),
242//! * [`tokio::process`], for spawning and managing child processes (enabled by
243//!   the "process" feature flag).
244//!
245//! [`tokio::io`]: crate::io
246//! [`AsyncRead`]: crate::io::AsyncRead
247//! [`AsyncWrite`]: crate::io::AsyncWrite
248//! [`AsyncBufRead`]: crate::io::AsyncBufRead
249//! [`std::io`]: std::io
250//! [`tokio::net`]: crate::net
251//! [TCP]: crate::net::tcp
252//! [UDP]: crate::net::UdpSocket
253//! [UDS]: crate::net::unix
254//! [`tokio::fs`]: crate::fs
255//! [`std::fs`]: std::fs
256//! [`tokio::signal`]: crate::signal
257//! [`tokio::process`]: crate::process
258//!
259//! # Examples
260//!
261//! A simple TCP echo server:
262//!
263//! ```no_run
264//! use tokio::net::TcpListener;
265//! use tokio::io::{AsyncReadExt, AsyncWriteExt};
266//!
267//! #[tokio::main]
268//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
269//!     let listener = TcpListener::bind("127.0.0.1:8080").await?;
270//!
271//!     loop {
272//!         let (mut socket, _) = listener.accept().await?;
273//!
274//!         tokio::spawn(async move {
275//!             let mut buf = [0; 1024];
276//!
277//!             // In a loop, read data from the socket and write the data back.
278//!             loop {
279//!                 let n = match socket.read(&mut buf).await {
280//!                     // socket closed
281//!                     Ok(n) if n == 0 => return,
282//!                     Ok(n) => n,
283//!                     Err(e) => {
284//!                         eprintln!("failed to read from socket; err = {:?}", e);
285//!                         return;
286//!                     }
287//!                 };
288//!
289//!                 // Write the data back
290//!                 if let Err(e) = socket.write_all(&buf[0..n]).await {
291//!                     eprintln!("failed to write to socket; err = {:?}", e);
292//!                     return;
293//!                 }
294//!             }
295//!         });
296//!     }
297//! }
298//! ```
299//!
300//! ## Feature flags
301//!
302//! Tokio uses a set of [feature flags] to reduce the amount of compiled code. It
303//! is possible to just enable certain features over others. By default, Tokio
304//! does not enable any features but allows one to enable a subset for their use
305//! case. Below is a list of the available feature flags. You may also notice
306//! above each function, struct and trait there is listed one or more feature flags
307//! that are required for that item to be used. If you are new to Tokio it is
308//! recommended that you use the `full` feature flag which will enable all public APIs.
309//! Beware though that this will pull in many extra dependencies that you may not
310//! need.
311//!
312//! - `full`: Enables all features listed below except `test-util` and `tracing`.
313//! - `rt`: Enables `tokio::spawn`, the current-thread scheduler,
314//!         and non-scheduler utilities.
315//! - `rt-multi-thread`: Enables the heavier, multi-threaded, work-stealing scheduler.
316//! - `io-util`: Enables the IO based `Ext` traits.
317//! - `io-std`: Enable `Stdout`, `Stdin` and `Stderr` types.
318//! - `net`: Enables `tokio::net` types such as `TcpStream`, `UnixStream` and
319//!          `UdpSocket`, as well as (on Unix-like systems) `AsyncFd` and (on
320//!          FreeBSD) `PollAio`.
321//! - `time`: Enables `tokio::time` types and allows the schedulers to enable
322//!           the built in timer.
323//! - `process`: Enables `tokio::process` types.
324//! - `macros`: Enables `#[tokio::main]` and `#[tokio::test]` macros.
325//! - `sync`: Enables all `tokio::sync` types.
326//! - `signal`: Enables all `tokio::signal` types.
327//! - `fs`: Enables `tokio::fs` types.
328//! - `test-util`: Enables testing based infrastructure for the Tokio runtime.
329//!
330//! _Note: `AsyncRead` and `AsyncWrite` traits do not require any features and are
331//! always available._
332//!
333//! ### Internal features
334//!
335//! These features do not expose any new API, but influence internal
336//! implementation aspects of Tokio, and can pull in additional
337//! dependencies.
338//!
339//! - `parking_lot`: As a potential optimization, use the _parking_lot_ crate's
340//! synchronization primitives internally. MSRV may increase according to the
341//! _parking_lot_ release in use.
342//!
343//! ### Unstable features
344//!
345//! Some feature flags are only available when specifying the `tokio_unstable` flag:
346//!
347//! - `tracing`: Enables tracing events.
348//!
349//! Likewise, some parts of the API are only available with the same flag:
350//!
351//! - [`task::Builder`]
352//! - Some methods on [`task::JoinSet`]
353//! - [`runtime::RuntimeMetrics`]
354//! - [`runtime::Builder::unhandled_panic`]
355//! - [`task::Id`]
356//!
357//! This flag enables **unstable** features. The public API of these features
358//! may break in 1.x releases. To enable these features, the `--cfg
359//! tokio_unstable` argument must be passed to `rustc` when compiling. This
360//! serves to explicitly opt-in to features which may break semver conventions,
361//! since Cargo [does not yet directly support such opt-ins][unstable features].
362//!
363//! You can specify it in your project's `.cargo/config.toml` file:
364//!
365//! ```toml
366//! [build]
367//! rustflags = ["--cfg", "tokio_unstable"]
368//! ```
369//!
370//! Alternatively, you can specify it with an environment variable:
371//!
372//! ```sh
373//! ## Many *nix shells:
374//! export RUSTFLAGS="--cfg tokio_unstable"
375//! cargo build
376//! ```
377//!
378//! ```powershell
379//! ## Windows PowerShell:
380//! $Env:RUSTFLAGS="--cfg tokio_unstable"
381//! cargo build
382//! ```
383//!
384//! [unstable features]: https://internals.rust-lang.org/t/feature-request-unstable-opt-in-non-transitive-crate-features/16193#why-not-a-crate-feature-2
385//! [feature flags]: https://doc.rust-lang.org/cargo/reference/manifest.html#the-features-section
386//!
387//! ## WASM support
388//!
389//! Tokio has some limited support for the WASM platform. Without the
390//! `tokio_unstable` flag, the following features are supported:
391//!
392//!  * `sync`
393//!  * `macros`
394//!  * `io-util`
395//!  * `rt`
396//!  * `time`
397//!
398//! Enabling any other feature (including `full`) will cause a compilation
399//! failure.
400//!
401//! The `time` module will only work on WASM platforms that have support for
402//! timers (e.g. wasm32-wasi). The timing functions will panic if used on a WASM
403//! platform that does not support timers.
404//!
405//! Note also that if the runtime becomes indefinitely idle, it will panic
406//! immediately instead of blocking forever. On platforms that don't support
407//! time, this means that the runtime can never be idle in any way.
408//!
409//! ### Unstable WASM support
410//!
411//! Tokio also has unstable support for some additional WASM features. This
412//! requires the use of the `tokio_unstable` flag.
413//!
414//! Using this flag enables the use of `tokio::net` on the wasm32-wasi target.
415//! However, not all methods are available on the networking types as WASI
416//! currently does not support the creation of new sockets from within WASM.
417//! Because of this, sockets must currently be created via the `FromRawFd`
418//! trait.
419
420// Test that pointer width is compatible. This asserts that e.g. usize is at
421// least 32 bits, which a lot of components in Tokio currently assumes.
422//
423// TODO: improve once we have MSRV access to const eval to make more flexible.
424#[cfg(not(any(
425    target_pointer_width = "32",
426    target_pointer_width = "64",
427    target_pointer_width = "128"
428)))]
429compile_error! {
430    "Tokio requires the platform pointer width to be 32, 64, or 128 bits"
431}
432
433// Ensure that our build script has correctly set cfg flags for wasm.
434//
435// Each condition is written all(a, not(b)). This should be read as
436// "if a, then we must also have b".
437#[cfg(any(
438    all(target_arch = "wasm32", not(tokio_wasm)),
439    all(target_arch = "wasm64", not(tokio_wasm)),
440    all(target_family = "wasm", not(tokio_wasm)),
441    all(target_os = "wasi", not(tokio_wasm)),
442    all(target_os = "wasi", not(tokio_wasi)),
443    all(target_os = "wasi", tokio_wasm_not_wasi),
444    all(tokio_wasm, not(any(target_arch = "wasm32", target_arch = "wasm64"))),
445    all(tokio_wasm_not_wasi, not(tokio_wasm)),
446    all(tokio_wasi, not(tokio_wasm))
447))]
448compile_error!("Tokio's build script has incorrectly detected wasm.");
449
450#[cfg(all(
451    not(tokio_unstable),
452    tokio_wasm,
453    any(
454        feature = "fs",
455        feature = "io-std",
456        feature = "net",
457        feature = "process",
458        feature = "rt-multi-thread",
459        feature = "signal"
460    )
461))]
462compile_error!("Only features sync,macros,io-util,rt,time are supported on wasm.");
463
464// Includes re-exports used by macros.
465//
466// This module is not intended to be part of the public API. In general, any
467// `doc(hidden)` code is not part of Tokio's public and stable API.
468#[macro_use]
469#[doc(hidden)]
470pub mod macros;
471
472cfg_fs! {
473    pub mod fs;
474}
475
476mod future;
477
478pub mod io;
479pub mod net;
480
481mod loom;
482mod park;
483
484cfg_process! {
485    pub mod process;
486}
487
488#[cfg(any(
489    feature = "fs",
490    feature = "io-std",
491    feature = "net",
492    all(windows, feature = "process"),
493))]
494mod blocking;
495
496cfg_rt! {
497    pub mod runtime;
498}
499cfg_not_rt! {
500    cfg_io_driver_impl! {
501        pub(crate) mod runtime;
502    }
503}
504
505pub(crate) mod coop;
506
507cfg_signal! {
508    pub mod signal;
509}
510
511cfg_signal_internal! {
512    #[cfg(not(feature = "signal"))]
513    #[allow(dead_code)]
514    #[allow(unreachable_pub)]
515    pub(crate) mod signal;
516}
517
518cfg_sync! {
519    pub mod sync;
520}
521cfg_not_sync! {
522    mod sync;
523}
524
525pub mod task;
526cfg_rt! {
527    pub use task::spawn;
528}
529
530cfg_time! {
531    pub mod time;
532}
533
534mod util;
535
536/// Due to the `Stream` trait's inclusion in `std` landing later than Tokio's 1.0
537/// release, most of the Tokio stream utilities have been moved into the [`tokio-stream`]
538/// crate.
539///
540/// # Why was `Stream` not included in Tokio 1.0?
541///
542/// Originally, we had planned to ship Tokio 1.0 with a stable `Stream` type
543/// but unfortunately the [RFC] had not been merged in time for `Stream` to
544/// reach `std` on a stable compiler in time for the 1.0 release of Tokio. For
545/// this reason, the team has decided to move all `Stream` based utilities to
546/// the [`tokio-stream`] crate. While this is not ideal, once `Stream` has made
547/// it into the standard library and the MSRV period has passed, we will implement
548/// stream for our different types.
549///
550/// While this may seem unfortunate, not all is lost as you can get much of the
551/// `Stream` support with `async/await` and `while let` loops. It is also possible
552/// to create a `impl Stream` from `async fn` using the [`async-stream`] crate.
553///
554/// [`tokio-stream`]: https://docs.rs/tokio-stream
555/// [`async-stream`]: https://docs.rs/async-stream
556/// [RFC]: https://github.com/rust-lang/rfcs/pull/2996
557///
558/// # Example
559///
560/// Convert a [`sync::mpsc::Receiver`] to an `impl Stream`.
561///
562/// ```rust,no_run
563/// use tokio::sync::mpsc;
564///
565/// let (tx, mut rx) = mpsc::channel::<usize>(16);
566///
567/// let stream = async_stream::stream! {
568///     while let Some(item) = rx.recv().await {
569///         yield item;
570///     }
571/// };
572/// ```
573pub mod stream {}
574
575// local re-exports of platform specific things, allowing for decent
576// documentation to be shimmed in on docs.rs
577
578#[cfg(docsrs)]
579pub mod doc;
580
581#[cfg(docsrs)]
582#[allow(unused)]
583pub(crate) use self::doc::os;
584
585#[cfg(not(docsrs))]
586#[allow(unused)]
587pub(crate) use std::os;
588
589#[cfg(docsrs)]
590#[allow(unused)]
591pub(crate) use self::doc::winapi;
592
593#[cfg(all(not(docsrs), windows, feature = "net"))]
594#[allow(unused)]
595pub(crate) use winapi;
596
597cfg_macros! {
598    /// Implementation detail of the `select!` macro. This macro is **not**
599    /// intended to be used as part of the public API and is permitted to
600    /// change.
601    #[doc(hidden)]
602    pub use tokio_macros::select_priv_declare_output_enum;
603
604    /// Implementation detail of the `select!` macro. This macro is **not**
605    /// intended to be used as part of the public API and is permitted to
606    /// change.
607    #[doc(hidden)]
608    pub use tokio_macros::select_priv_clean_pattern;
609
610    cfg_rt! {
611        #[cfg(feature = "rt-multi-thread")]
612        #[cfg(not(test))] // Work around for rust-lang/rust#62127
613        #[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
614        #[doc(inline)]
615        pub use tokio_macros::main;
616
617        #[cfg(feature = "rt-multi-thread")]
618        #[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
619        #[doc(inline)]
620        pub use tokio_macros::test;
621
622        cfg_not_rt_multi_thread! {
623            #[cfg(not(test))] // Work around for rust-lang/rust#62127
624            #[doc(inline)]
625            pub use tokio_macros::main_rt as main;
626
627            #[doc(inline)]
628            pub use tokio_macros::test_rt as test;
629        }
630    }
631
632    // Always fail if rt is not enabled.
633    cfg_not_rt! {
634        #[cfg(not(test))]
635        #[doc(inline)]
636        pub use tokio_macros::main_fail as main;
637
638        #[doc(inline)]
639        pub use tokio_macros::test_fail as test;
640    }
641}
642
643// TODO: rm
644#[cfg(feature = "io-util")]
645#[cfg(test)]
646fn is_unpin<T: Unpin>() {}