# tokio 1.53.1

> A runtime for writing reliable network applications without compromising speed.

## tokio

A runtime for writing reliable network applications without compromising speed.

Tokio is an event-driven, non-blocking I/O platform for writing asynchronous
applications with the Rust programming language. At a high level, it
provides a few major components:

* Tools for [working with asynchronous tasks][tasks], including
  [synchronization primitives and channels][sync] and [timeouts, sleeps, and
  intervals][time].
* APIs for [performing asynchronous I/O][io], including [TCP and UDP][net] sockets,
  [filesystem][fs] operations, and [process] and [signal] management.
* A [runtime] for executing asynchronous code, including a task scheduler,
  an I/O driver backed by the operating system's event queue (`epoll`, `kqueue`,
  `IOCP`, etc...), and a high performance timer.

Guide level documentation is found on the [website].

[tasks]: #working-with-tasks
[sync]: crate::sync
[time]: crate::time
[io]: #asynchronous-io
[net]: crate::net
[fs]: crate::fs
[process]: crate::process
[signal]: crate::signal
[fs]: crate::fs
[runtime]: crate::runtime
[website]: https://tokio.rs/tokio/tutorial

### tokio › A Tour of Tokio

Tokio consists of a number of modules that provide a range of functionality
essential for implementing asynchronous applications in Rust. In this
section, we will take a brief tour of Tokio, summarizing the major APIs and
their uses.

The easiest way to get started is to enable all features. Do this by
enabling the `full` feature flag:

```toml
tokio = { version = "1", features = ["full"] }
```

### tokio › Authoring applications

Tokio is great for writing applications and most users in this case shouldn't
worry too much about what features they should pick. If you're unsure, we suggest
going with `full` to ensure that you don't run into any road blocks while you're
building your application.

### tokio › Example

This example shows the quickest way to get started with Tokio.

```toml
tokio = { version = "1", features = ["full"] }
```

### tokio › Authoring libraries

As a library author your goal should be to provide the lightest weight crate
that is based on Tokio. To achieve this you should ensure that you only enable
the features you need. This allows users to pick up your crate without having
to enable unnecessary features.

### tokio › Example

This example shows how you may want to import features for a library that just
needs to `tokio::spawn` and use a `TcpStream`.

```toml
tokio = { version = "1", features = ["rt", "net"] }
```

### tokio › Working With Tasks

Asynchronous programs in Rust are based around lightweight, non-blocking
units of execution called [_tasks_][tasks]. The [`tokio::task`] module provides
important tools for working with tasks:

* The [`spawn`] function and [`JoinHandle`] type, for scheduling a new task
  on the Tokio runtime and awaiting the output of a spawned task, respectively,
* Functions for [running blocking operations][blocking] in an asynchronous
  task context.

The [`tokio::task`] module is present only when the "rt" feature flag
is enabled.

[tasks]: task/index.html#what-are-tasks
[`tokio::task`]: crate::task
[`spawn`]: crate::task::spawn()
[`JoinHandle`]: crate::task::JoinHandle
[blocking]: task/index.html#blocking-and-yielding

The [`tokio::sync`] module contains synchronization primitives to use when
needing to communicate or share data. These include:

* channels ([`oneshot`], [`mpsc`], [`watch`], and [`broadcast`]), for sending values
  between tasks,
* a non-blocking [`Mutex`], for controlling access to a shared, mutable
  value,
* an asynchronous [`Barrier`] type, for multiple tasks to synchronize before
  beginning a computation.

The `tokio::sync` module is present only when the "sync" feature flag is
enabled.

[`tokio::sync`]: crate::sync
[`Mutex`]: crate::sync::Mutex
[`Barrier`]: crate::sync::Barrier
[`oneshot`]: crate::sync::oneshot
[`mpsc`]: crate::sync::mpsc
[`watch`]: crate::sync::watch
[`broadcast`]: crate::sync::broadcast

The [`tokio::time`] module provides utilities for tracking time and
scheduling work. This includes functions for setting [timeouts][timeout] for
tasks, [sleeping][sleep] work to run in the future, or [repeating an operation at an
interval][interval].

In order to use `tokio::time`, the "time" feature flag must be enabled.

[`tokio::time`]: crate::time
[sleep]: crate::time::sleep()
[interval]: crate::time::interval()
[timeout]: crate::time::timeout()

Finally, Tokio provides a _runtime_ for executing asynchronous tasks. Most
applications can use the [`#[tokio::main]`][main] macro to run their code on the
Tokio runtime. However, this macro provides only basic configuration options. As
an alternative, the [`tokio::runtime`] module provides more powerful APIs for configuring
and managing runtimes. You should use that module if the `#[tokio::main]` macro doesn't
provide the functionality you need.

Using the runtime requires the "rt" or "rt-multi-thread" feature flags, to
enable the current-thread [single-threaded scheduler][rt] and the [multi-thread
scheduler][rt-multi-thread], respectively. See the [`runtime` module
documentation][rt-features] for details. In addition, the "macros" feature
flag enables the `#[tokio::main]` and `#[tokio::test]` attributes.

[main]: attr.main.html
[`tokio::runtime`]: crate::runtime
[`Builder`]: crate::runtime::Builder
[`Runtime`]: crate::runtime::Runtime
[rt]: runtime/index.html#current-thread-scheduler
[rt-multi-thread]: runtime/index.html#multi-thread-scheduler
[rt-features]: runtime/index.html#runtime-scheduler

### tokio › CPU-bound tasks and blocking code

Tokio is able to concurrently run many tasks on a few threads by repeatedly
swapping the currently running task on each thread. However, this kind of
swapping can only happen at `.await` points, so code that spends a long time
without reaching an `.await` will prevent other tasks from running. To
combat this, Tokio provides two kinds of threads: Core threads and blocking threads.

The core threads are where all asynchronous code runs, and Tokio will by default
spawn one for each CPU core. You can use the environment variable `TOKIO_WORKER_THREADS`
to override the default value.

The blocking threads are spawned on demand, can be used to run blocking code
that would otherwise block other tasks from running and are kept alive when
not used for a certain amount of time which can be configured with [`thread_keep_alive`].
Since it is not possible for Tokio to swap out blocking tasks, like it
can do with asynchronous code, the upper limit on the number of blocking
threads is very large. These limits can be configured on the [`Builder`].

To spawn a blocking task, you should use the [`spawn_blocking`] function.

[`Builder`]: crate::runtime::Builder
[`spawn_blocking`]: crate::task::spawn_blocking()
[`thread_keep_alive`]: crate::runtime::Builder::thread_keep_alive()

```
# #[cfg(not(target_family = "wasm"))]
# {
#[tokio::main]
async fn main() {
    // This is running on a core thread.

    let blocking_task = tokio::task::spawn_blocking(|| {
        // This is running on a blocking thread.
        // Blocking here is ok.
    });

    // We can wait for the blocking task like this:
    // If the blocking task panics, the unwrap below will propagate the
    // panic.
    blocking_task.await.unwrap();
}
# }
```

If your code is CPU-bound and you wish to limit the number of threads used
to run it, you should use a separate thread pool dedicated to CPU bound tasks.
For example, you could consider using the [rayon] library for CPU-bound
tasks. It is also possible to create an extra Tokio runtime dedicated to
CPU-bound tasks, but if you do this, you should be careful that the extra
runtime runs _only_ CPU-bound tasks, as IO-bound tasks on that runtime
will behave poorly.

Hint: If using rayon, you can use a [`oneshot`] channel to send the result back
to Tokio when the rayon task finishes.

[rayon]: https://docs.rs/rayon
[`oneshot`]: crate::sync::oneshot

### tokio › Asynchronous IO

As well as scheduling and running tasks, Tokio provides everything you need
to perform input and output asynchronously.

The [`tokio::io`] module provides Tokio's asynchronous core I/O primitives,
the [`AsyncRead`], [`AsyncWrite`], and [`AsyncBufRead`] traits. In addition,
when the "io-util" feature flag is enabled, it also provides combinators and
functions for working with these traits, forming as an asynchronous
counterpart to [`std::io`].

Tokio also includes APIs for performing various kinds of I/O and interacting
with the operating system asynchronously. These include:

* [`tokio::net`], which contains non-blocking versions of [TCP], [UDP], and
  [Unix Domain Sockets][UDS] (enabled by the "net" feature flag),
* [`tokio::fs`], similar to [`std::fs`] but for performing filesystem I/O
  asynchronously (enabled by the "fs" feature flag),
* [`tokio::signal`], for asynchronously handling Unix and Windows OS signals
  (enabled by the "signal" feature flag),
* [`tokio::process`], for spawning and managing child processes (enabled by
  the "process" feature flag).

[`tokio::io`]: crate::io
[`AsyncRead`]: crate::io::AsyncRead
[`AsyncWrite`]: crate::io::AsyncWrite
[`AsyncBufRead`]: crate::io::AsyncBufRead
[`std::io`]: std::io
[`tokio::net`]: crate::net
[TCP]: crate::net::tcp
[UDP]: crate::net::UdpSocket
[UDS]: crate::net::unix
[`tokio::fs`]: crate::fs
[`std::fs`]: std::fs
[`tokio::signal`]: crate::signal
[`tokio::process`]: crate::process

### tokio › Examples

A simple TCP echo server:

```no_run
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::net::TcpListener;
use tokio::io::{AsyncReadExt, AsyncWriteExt};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let listener = TcpListener::bind("127.0.0.1:8080").await?;

    loop {
        let (mut socket, _) = listener.accept().await?;

        tokio::spawn(async move {
            let mut buf = [0; 1024];

            // In a loop, read data from the socket and write the data back.
            loop {
                let n = match socket.read(&mut buf).await {
                    // socket closed
                    Ok(0) => return,
                    Ok(n) => n,
                    Err(e) => {
                        eprintln!("failed to read from socket; err = {:?}", e);
                        return;
                    }
                };

                // Write the data back
                if let Err(e) = socket.write_all(&buf[0..n]).await {
                    eprintln!("failed to write to socket; err = {:?}", e);
                    return;
                }
            }
        });
    }
}
# }
```

### tokio › Feature flags

Tokio uses a set of [feature flags] to reduce the amount of compiled code. It
is possible to just enable certain features over others. By default, Tokio
does not enable any features but allows one to enable a subset for their use
case. Below is a list of the available feature flags. You may also notice
above each function, struct and trait there is listed one or more feature flags
that are required for that item to be used. If you are new to Tokio it is
recommended that you use the `full` feature flag which will enable all public APIs.
Beware though that this will pull in many extra dependencies that you may not
need.

- `full`: Enables all features listed below except `test-util` and unstable features.
- `rt`: Enables `tokio::spawn`, the current-thread scheduler,
  and non-scheduler utilities.
- `rt-multi-thread`: Enables the heavier, multi-threaded, work-stealing scheduler.
- `io-util`: Enables the IO based `Ext` traits.
- `io-std`: Enable `Stdout`, `Stdin` and `Stderr` types.
- `net`: Enables `tokio::net` types such as `TcpStream`, `UnixStream` and
  `UdpSocket`, as well as (on Unix-like systems) `AsyncFd` and (on
  FreeBSD) `PollAio`.
- `time`: Enables `tokio::time` types and allows the schedulers to enable
  the built-in timer.
- `process`: Enables `tokio::process` types.
- `macros`: Enables `#[tokio::main]` and `#[tokio::test]` macros.
- `sync`: Enables all `tokio::sync` types.
- `signal`: Enables all `tokio::signal` types.
- `fs`: Enables `tokio::fs` types.
- `test-util`: Enables testing based infrastructure for the Tokio runtime.
- `parking_lot`: As a potential optimization, use the [`parking_lot`] crate's
  synchronization primitives internally. Also, this
  dependency is necessary to construct some of our primitives
  in a `const` context. `MSRV` may increase according to the
  [`parking_lot`] release in use.

_Note: `AsyncRead` and `AsyncWrite` traits do not require any features and are
always available._

### tokio › Unstable features

Some feature flags are only available when specifying the `tokio_unstable` flag:

- `tracing`: Enables tracing events.
- `schedule-latency`: Allows measurement of task scheduling latencies.
- `io-uring`: Enables `io-uring` (Linux only).
- `taskdump`: Enables `taskdump` (Linux only).

Likewise, this flag enables access to unstable APIs.

This flag enables **unstable** features. The public API of these features
may break in 1.x releases. To enable these features, the `--cfg
tokio_unstable` argument must be passed to `rustc` when compiling. This
serves to explicitly opt-in to features which may break semver conventions,
since Cargo [does not yet directly support such opt-ins][unstable features].

You can specify it in your project's `.cargo/config.toml` file:

```toml
[build]
rustflags = ["--cfg", "tokio_unstable"]
```

<div class="warning">
The <code>[build]</code> section does <strong>not</strong> go in a
<code>Cargo.toml</code> file. Instead it must be placed in the Cargo config
file <code>.cargo/config.toml</code>.
</div>

Alternatively, you can specify it with an environment variable:

```sh
## Many *nix shells:
export RUSTFLAGS="--cfg tokio_unstable"
cargo build
```

```powershell
## Windows PowerShell:
$Env:RUSTFLAGS="--cfg tokio_unstable"
cargo build
```

[unstable features]: https://internals.rust-lang.org/t/feature-request-unstable-opt-in-non-transitive-crate-features/16193#why-not-a-crate-feature-2
[feature flags]: https://doc.rust-lang.org/cargo/reference/manifest.html#the-features-section

### tokio › Supported platforms

Tokio currently guarantees support for the following platforms:

 * Linux
 * Windows
 * Android (API level 21)
 * macOS
 * iOS
 * FreeBSD

Tokio will continue to support these platforms in the future. However,
future releases may change requirements such as the minimum required libc
version on Linux, the API level on Android, or the supported FreeBSD
release.

Beyond the above platforms, Tokio is intended to work on all platforms
supported by the mio crate. You can find a longer list [in mio's
documentation][mio-supported]. However, these additional platforms may
become unsupported in the future.

Note that Wine is considered to be a different platform from Windows. See
mio's documentation for more information on Wine support.

[mio-supported]: https://crates.io/crates/mio#platforms

### tokio › `WASM` support

Tokio has some limited support for the `WASM` platform. Without the
`tokio_unstable` flag, the following features are supported:

 * `sync`
 * `macros`
 * `io-util`
 * `rt`
 * `time`

Enabling any other feature (including `full`) will cause a compilation
failure.

The `time` module will only work on `WASM` platforms that have support for
timers (e.g. wasm32-wasi). The timing functions will panic if used on a `WASM`
platform that does not support timers.

Note also that if the runtime becomes indefinitely idle, it will panic
immediately instead of blocking forever. On platforms that don't support
time, this means that the runtime can never be idle in any way.

### tokio › Unstable `WASM` support

Tokio also has unstable support for some additional `WASM` features. This
requires the use of the `tokio_unstable` flag.

Using this flag enables the use of `tokio::net` on the wasm32-wasi target.
However, not all methods are available on the networking types as `WASI`
currently does not support the creation of new sockets from within `WASM`.
Because of this, sockets must currently be created via the `FromRawFd`
trait.

## tokio::doc (module)

Types which are documented locally in the Tokio crate, but does not actually
live here.

**Note** this module is only visible on docs.rs, you cannot use it directly
in your own code.

## tokio::doc::os (module)

See [`std::os`](https://doc.rust-lang.org/std/os/index.html).

## tokio::doc::os::windows (module)

Platform-specific extensions to `std` for Windows.

See [`std::os::windows`](https://doc.rust-lang.org/std/os/windows/index.html).

## tokio::doc::os::windows::io (module)

Windows-specific extensions to general I/O primitives.

See [`std::os::windows::io`](https://doc.rust-lang.org/std/os/windows/io/index.html).

## tokio::fs (module)

Asynchronous file utilities.

This module contains utility methods for working with the file system
asynchronously. This includes reading/writing to files, and working with
directories.

Be aware that most operating systems do not provide asynchronous file system
APIs. Because of that, Tokio will use ordinary blocking file operations
behind the scenes. This is done using the [`spawn_blocking`] threadpool to
run them in the background.

The `tokio::fs` module should only be used for ordinary files. Trying to use
it with e.g., a named pipe on Linux can result in surprising behavior,
such as hangs during runtime shutdown. For special files, you should use a
dedicated type such as [`tokio::net::unix::pipe`] or [`AsyncFd`] instead.

Currently, Tokio will always use [`spawn_blocking`] on all platforms, but it
may be changed to use asynchronous file system APIs such as io_uring in the
future.

### tokio::fs (module) › Usage

The easiest way to use this module is to use the utility functions that
operate on entire files:

 * [`tokio::fs::read`](fn@crate::fs::read)
 * [`tokio::fs::read_to_string`](fn@crate::fs::read_to_string)
 * [`tokio::fs::write`](fn@crate::fs::write)

The two `read` functions reads the entire file and returns its contents.
The `write` function takes the contents of the file and writes those
contents to the file. It overwrites the existing file, if any.

For example, to read the file:

```
# async fn dox() -> std::io::Result<()> {
let contents = tokio::fs::read_to_string("my_file.txt").await?;

println!("File has {} lines.", contents.lines().count());
# Ok(())
# }
```

To overwrite the file:

```
# async fn dox() -> std::io::Result<()> {
let contents = "First line.\nSecond line.\nThird line.\n";

tokio::fs::write("my_file.txt", contents.as_bytes()).await?;
# Ok(())
# }
```

### tokio::fs (module) › Using `File`

The main type for interacting with files is [`File`]. It can be used to read
from and write to a given file. This is done using the [`AsyncRead`] and
[`AsyncWrite`] traits. This type is generally used when you want to do
something more complex than just reading or writing the entire contents in
one go.

**Note:** It is important to use [`flush`] when writing to a Tokio
[`File`]. This is because calls to `write` will return before the write has
finished, and [`flush`] will wait for the write to finish. (The write will
happen even if you don't flush; it will just happen later.) This is
different from [`std::fs::File`], and is due to the fact that `File` uses
`spawn_blocking` behind the scenes.

For example, to count the number of lines in a file without loading the
entire file into memory:

```no_run
use tokio::fs::File;
use tokio::io::AsyncReadExt;

# async fn dox() -> std::io::Result<()> {
let mut file = File::open("my_file.txt").await?;

let mut chunk = vec![0; 4096];
let mut number_of_lines = 0;
loop {
    let len = file.read(&mut chunk).await?;
    if len == 0 {
        // Length of zero means end of file.
        break;
    }
    for &b in &chunk[..len] {
        if b == b'\n' {
            number_of_lines += 1;
        }
    }
}

println!("File has {} lines.", number_of_lines);
# Ok(())
# }
```

For example, to write a file line-by-line:

```no_run
use tokio::fs::File;
use tokio::io::AsyncWriteExt;

# async fn dox() -> std::io::Result<()> {
let mut file = File::create("my_file.txt").await?;

file.write_all(b"First line.\n").await?;
file.write_all(b"Second line.\n").await?;
file.write_all(b"Third line.\n").await?;

// Remember to call `flush` after writing!
file.flush().await?;
# Ok(())
# }
```

### tokio::fs (module) › Tuning your file IO

Tokio's file uses [`spawn_blocking`] behind the scenes, and this has serious
performance consequences. To get good performance with file IO on Tokio, it
is recommended to batch your operations into as few `spawn_blocking` calls
as possible.

One example of this difference can be seen by comparing the two reading
examples above. The first example uses [`tokio::fs::read`], which reads the
entire file in a single `spawn_blocking` call, and then returns it. The
second example will read the file in chunks using many `spawn_blocking`
calls. This means that the second example will most likely be more expensive
for large files. (Of course, using chunks may be necessary for very large
files that don't fit in memory.)

The following examples will show some strategies for this:

When creating a file, write the data to a `String` or `Vec<u8>` and then
write the entire file in a single `spawn_blocking` call with
`tokio::fs::write`.

```no_run
# async fn dox() -> std::io::Result<()> {
let mut contents = String::new();

contents.push_str("First line.\n");
contents.push_str("Second line.\n");
contents.push_str("Third line.\n");

tokio::fs::write("my_file.txt", contents.as_bytes()).await?;
# Ok(())
# }
```

Use [`BufReader`] and [`BufWriter`] to buffer many small reads or writes
into a few large ones. This example will most likely only perform one
`spawn_blocking` call.

```no_run
use tokio::fs::File;
use tokio::io::{AsyncWriteExt, BufWriter};

# async fn dox() -> std::io::Result<()> {
let mut file = BufWriter::new(File::create("my_file.txt").await?);

file.write_all(b"First line.\n").await?;
file.write_all(b"Second line.\n").await?;
file.write_all(b"Third line.\n").await?;

// Due to the BufWriter, the actual write and spawn_blocking
// call happens when you flush.
file.flush().await?;
# Ok(())
# }
```

Manually use [`std::fs`] inside [`spawn_blocking`].

```no_run
use std::fs::File;
use std::io::{self, Write};
use tokio::task::spawn_blocking;

# async fn dox() -> std::io::Result<()> {
spawn_blocking(move || {
    let mut file = File::create("my_file.txt")?;

    file.write_all(b"First line.\n")?;
    file.write_all(b"Second line.\n")?;
    file.write_all(b"Third line.\n")?;

    // Unlike Tokio's file, the std::fs file does
    // not need flush.

    io::Result::Ok(())
}).await.unwrap()?;
# Ok(())
# }
```

It's also good to be aware of [`File::set_max_buf_size`], which controls the
maximum amount of bytes that Tokio's [`File`] will read or write in a single
[`spawn_blocking`] call. The default is two megabytes, but this is subject
to change.

[`spawn_blocking`]: fn@crate::task::spawn_blocking
[`AsyncRead`]: trait@crate::io::AsyncRead
[`AsyncWrite`]: trait@crate::io::AsyncWrite
[`BufReader`]: struct@crate::io::BufReader
[`BufWriter`]: struct@crate::io::BufWriter
[`tokio::net::unix::pipe`]: crate::net::unix::pipe
[`AsyncFd`]: crate::io::unix::AsyncFd
[`flush`]: crate::io::AsyncWriteExt::flush
[`tokio::fs::read`]: fn@crate::fs::read

## tokio::io (module)

Traits, helpers, and type definitions for asynchronous I/O functionality.

This module is the asynchronous version of `std::io`. Primarily, it
defines two traits, [`AsyncRead`] and [`AsyncWrite`], which are asynchronous
versions of the [`Read`] and [`Write`] traits in the standard library.

### tokio::io (module) › `AsyncRead` and `AsyncWrite`

Like the standard library's [`Read`] and [`Write`] traits, [`AsyncRead`] and
[`AsyncWrite`] provide the most general interface for reading and writing
input and output. Unlike the standard library's traits, however, they are
_asynchronous_ &mdash; meaning that reading from or writing to a `tokio::io`
type will _yield_ to the Tokio scheduler when IO is not ready, rather than
blocking. This allows other tasks to run while waiting on IO.

Another difference is that `AsyncRead` and `AsyncWrite` only contain
core methods needed to provide asynchronous reading and writing
functionality. Instead, utility methods are defined in the [`AsyncReadExt`]
and [`AsyncWriteExt`] extension traits. These traits are automatically
implemented for all values that implement `AsyncRead` and `AsyncWrite`
respectively.

End users will rarely interact directly with `AsyncRead` and
`AsyncWrite`. Instead, they will use the async functions defined in the
extension traits. Library authors are expected to implement `AsyncRead`
and `AsyncWrite` in order to provide types that behave like byte streams.

Even with these differences, Tokio's `AsyncRead` and `AsyncWrite` traits
can be used in almost exactly the same manner as the standard library's
`Read` and `Write`. Most types in the standard library that implement `Read`
and `Write` have asynchronous equivalents in `tokio` that implement
`AsyncRead` and `AsyncWrite`, such as [`File`] and [`TcpStream`].

For example, the standard library documentation introduces `Read` by
[demonstrating][std_example] reading some bytes from a [`std::fs::File`]. We
can do the same with [`tokio::fs::File`][`File`]:

```no_run
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::io::{self, AsyncReadExt};
use tokio::fs::File;

#[tokio::main]
async fn main() -> io::Result<()> {
    let mut f = File::open("foo.txt").await?;
    let mut buffer = [0; 10];

    // read up to 10 bytes
    let n = f.read(&mut buffer).await?;

    println!("The bytes: {:?}", &buffer[..n]);
    Ok(())
}
# }
```

[`File`]: crate::fs::File
[`TcpStream`]: crate::net::TcpStream
[`std::fs::File`]: std::fs::File
[std_example]: std::io#read-and-write

### tokio::io (module) › Buffered Readers and Writers

Byte-based interfaces are unwieldy and can be inefficient, as we'd need to be
making near-constant calls to the operating system. To help with this,
`std::io` comes with [support for _buffered_ readers and writers][stdbuf],
and therefore, `tokio::io` does as well.

Tokio provides an async version of the [`std::io::BufRead`] trait,
[`AsyncBufRead`]; and async [`BufReader`] and [`BufWriter`] structs, which
wrap readers and writers. These wrappers use a buffer, reducing the number
of calls and providing nicer methods for accessing exactly what you want.

For example, [`BufReader`] works with the [`AsyncBufRead`] trait to add
extra methods to any async reader:

```no_run
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::io::{self, BufReader, AsyncBufReadExt};
use tokio::fs::File;

#[tokio::main]
async fn main() -> io::Result<()> {
    let f = File::open("foo.txt").await?;
    let mut reader = BufReader::new(f);
    let mut buffer = String::new();

    // read a line into buffer
    reader.read_line(&mut buffer).await?;

    println!("{}", buffer);
    Ok(())
}
# }
```

[`BufWriter`] doesn't add any new ways of writing; it just buffers every call
to [`write`](crate::io::AsyncWriteExt::write). However, you **must** flush
[`BufWriter`] to ensure that any buffered data is written.

```no_run
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::io::{self, BufWriter, AsyncWriteExt};
use tokio::fs::File;

#[tokio::main]
async fn main() -> io::Result<()> {
    let f = File::create("foo.txt").await?;
    {
        let mut writer = BufWriter::new(f);

        // Write a byte to the buffer.
        writer.write(&[42u8]).await?;

        // Flush the buffer before it goes out of scope.
        writer.flush().await?;

    } // Unless flushed or shut down, the contents of the buffer is discarded on drop.

    Ok(())
}
# }
```

[stdbuf]: std::io#bufreader-and-bufwriter
[`std::io::BufRead`]: std::io::BufRead
[`AsyncBufRead`]: crate::io::AsyncBufRead
[`BufReader`]: crate::io::BufReader
[`BufWriter`]: crate::io::BufWriter

### tokio::io (module) › Implementing `AsyncRead` and `AsyncWrite`

Because they are traits, we can implement [`AsyncRead`] and [`AsyncWrite`] for
our own types, as well. Note that these traits must only be implemented for
non-blocking I/O types that integrate with the futures type system. In
other words, these types must never block the thread, and instead the
current task is notified when the I/O resource is ready.

### tokio::io (module) › Conversion to and from Stream/Sink

It is often convenient to encapsulate the reading and writing of bytes in a
[`Stream`] or [`Sink`] of data.

Tokio provides simple wrappers for converting [`AsyncRead`] to [`Stream`]
and vice-versa in the [tokio-util] crate, see [`ReaderStream`] and
[`StreamReader`].

There are also utility traits that abstract the asynchronous buffering
necessary to write your own adaptors for encoding and decoding bytes to/from
your structured data, allowing to transform something that implements
[`AsyncRead`]/[`AsyncWrite`] into a [`Stream`]/[`Sink`], see [`Decoder`] and
[`Encoder`] in the [tokio-util::codec] module.

[tokio-util]: https://docs.rs/tokio-util
[tokio-util::codec]: https://docs.rs/tokio-util/latest/tokio_util/codec/index.html

### tokio::io (module) › Standard input and output

Tokio provides asynchronous APIs to standard [input], [output], and [error].
These APIs are very similar to the ones provided by `std`, but they also
implement [`AsyncRead`] and [`AsyncWrite`].

Note that the standard input / output APIs  **must** be used from the
context of the Tokio runtime, as they require Tokio-specific features to
function. Calling these functions outside of a Tokio runtime will panic.

[input]: fn@stdin
[output]: fn@stdout
[error]: fn@stderr

### tokio::io (module) › `std` re-exports

Additionally, [`Error`], [`ErrorKind`], [`Result`], and [`SeekFrom`] are
re-exported from `std::io` for ease of use.

[`AsyncRead`]: trait@AsyncRead
[`AsyncWrite`]: trait@AsyncWrite
[`AsyncReadExt`]: trait@AsyncReadExt
[`AsyncWriteExt`]: trait@AsyncWriteExt
["codec"]: https://docs.rs/tokio-util/latest/tokio_util/codec/index.html
[`Encoder`]: https://docs.rs/tokio-util/latest/tokio_util/codec/trait.Encoder.html
[`Decoder`]: https://docs.rs/tokio-util/latest/tokio_util/codec/trait.Decoder.html
[`ReaderStream`]: https://docs.rs/tokio-util/latest/tokio_util/io/struct.ReaderStream.html
[`StreamReader`]: https://docs.rs/tokio-util/latest/tokio_util/io/struct.StreamReader.html
[`Error`]: struct@Error
[`ErrorKind`]: enum@ErrorKind
[`Result`]: type@Result
[`Read`]: std::io::Read
[`SeekFrom`]: enum@SeekFrom
[`Sink`]: https://docs.rs/futures/0.3/futures/sink/trait.Sink.html
[`Stream`]: https://docs.rs/futures/0.3/futures/stream/trait.Stream.html
[`Write`]: std::io::Write

## tokio::io::bsd (module)

BSD-specific I/O types.

## tokio::io::unix (module)

Asynchronous IO structures specific to Unix-like operating systems.

## tokio::net (module)

TCP/UDP/Unix bindings for `tokio`.

This module contains the TCP/UDP/Unix networking types, similar to the standard
library, which can be used to implement networking protocols.

### tokio::net (module) › Organization

* [`TcpListener`] and [`TcpStream`] provide functionality for communication over TCP
* [`UdpSocket`] provides functionality for communication over UDP
* [`UnixListener`] and [`UnixStream`] provide functionality for communication over a
  Unix Domain Stream Socket **(available on Unix only)**
* [`UnixDatagram`] provides functionality for communication
  over Unix Domain Datagram Socket **(available on Unix only)**
* [`tokio::net::unix::pipe`] for FIFO pipes **(available on Unix only)**
* [`tokio::net::windows::named_pipe`] for Named Pipes **(available on Windows only)**

For IO resources not available in `tokio::net`, you can use [`AsyncFd`].

[`TcpListener`]: TcpListener
[`TcpStream`]: TcpStream
[`UdpSocket`]: UdpSocket
[`UnixListener`]: UnixListener
[`UnixStream`]: UnixStream
[`UnixDatagram`]: UnixDatagram
[`tokio::net::unix::pipe`]: unix::pipe
[`tokio::net::windows::named_pipe`]: windows::named_pipe
[`AsyncFd`]: crate::io::unix::AsyncFd

## tokio::net::tcp (module)

TCP utility types.

## tokio::net::unix (module)

Unix specific network types.

## tokio::net::unix::pipe (module)

Unix pipe types.

## tokio::net::windows (module)

Windows specific network types.

## tokio::net::windows::named_pipe (module)

Tokio support for [Windows named pipes].

[Windows named pipes]: https://docs.microsoft.com/en-us/windows/win32/ipc/named-pipes

## tokio::process (module)

An implementation of asynchronous process management for Tokio.

This module provides a [`Command`] struct that imitates the interface of the
[`std::process::Command`] type in the standard library, but provides asynchronous versions of
functions that create processes. These functions (`spawn`, `status`, `output` and their
variants) return "future aware" types that interoperate with Tokio. The asynchronous process
support is provided through signal handling on Unix and system APIs on Windows.

[`std::process::Command`]: std::process::Command

### tokio::process (module) › Examples

Here's an example program which will spawn `echo hello world` and then wait
for it complete.

```no_run
use tokio::process::Command;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // The usage is similar as with the standard library's `Command` type
    let mut child = Command::new("echo")
        .arg("hello")
        .arg("world")
        .spawn()
        .expect("failed to spawn");

    // Await until the command completes
    let status = child.wait().await?;
    println!("the command exited with: {}", status);
    Ok(())
}
```

Next, let's take a look at an example where we not only spawn `echo hello
world` but we also capture its output.

```no_run
use tokio::process::Command;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Like above, but use `output` which returns a future instead of
    // immediately returning the `Child`.
    let output = Command::new("echo").arg("hello").arg("world")
                        .output();

    let output = output.await?;

    assert!(output.status.success());
    assert_eq!(output.stdout, b"hello world\n");
    Ok(())
}
```

We can also read input line by line.

```no_run
use tokio::io::{BufReader, AsyncBufReadExt};
use tokio::process::Command;

use std::process::Stdio;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut cmd = Command::new("cat");

    // Specify that we want the command's standard output piped back to us.
    // By default, standard input/output/error will be inherited from the
    // current process (for example, this means that standard input will
    // come from the keyboard and standard output/error will go directly to
    // the terminal if this process is invoked from the command line).
    cmd.stdout(Stdio::piped());

    let mut child = cmd.spawn()
        .expect("failed to spawn command");

    let stdout = child.stdout.take()
        .expect("child did not have a handle to stdout");

    let mut reader = BufReader::new(stdout).lines();

    // Ensure the child process is spawned in the runtime so it can
    // make progress on its own while we await for any output.
    tokio::spawn(async move {
        let status = child.wait().await
            .expect("child process encountered an error");

        println!("child status was: {}", status);
    });

    while let Some(line) = reader.next_line().await? {
        println!("Line: {}", line);
    }

    Ok(())
}
```

Here is another example using `sort` writing into the child process
standard input, capturing the output of the sorted text.

```no_run
use tokio::io::AsyncWriteExt;
use tokio::process::Command;

use std::process::Stdio;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut cmd = Command::new("sort");

    // Specifying that we want pipe both the output and the input.
    // Similarly to capturing the output, by configuring the pipe
    // to stdin it can now be used as an asynchronous writer.
    cmd.stdout(Stdio::piped());
    cmd.stdin(Stdio::piped());

    let mut child = cmd.spawn().expect("failed to spawn command");

    // These are the animals we want to sort
    let animals: &[&str] = &["dog", "bird", "frog", "cat", "fish"];

    let mut stdin = child
        .stdin
        .take()
        .expect("child did not have a handle to stdin");

    // Write our animals to the child process
    // Note that the behavior of `sort` is to buffer _all input_ before writing any output.
    // In the general sense, it is recommended to write to the child in a separate task as
    // awaiting its exit (or output) to avoid deadlocks (for example, the child tries to write
    // some output but gets stuck waiting on the parent to read from it, meanwhile the parent
    // is stuck waiting to write its input completely before reading the output).
    stdin
        .write(animals.join("\n").as_bytes())
        .await
        .expect("could not write to stdin");

    // We drop the handle here which signals EOF to the child process.
    // This tells the child process that it there is no more data on the pipe.
    drop(stdin);

    let op = child.wait_with_output().await?;

    // Results should come back in sorted order
    assert_eq!(op.stdout, "bird\ncat\ndog\nfish\nfrog\n".as_bytes());

    Ok(())
}
```

With some coordination, we can also pipe the output of one command into
another.

```no_run
use tokio::join;
use tokio::process::Command;
use std::process::Stdio;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut echo = Command::new("echo")
        .arg("hello world!")
        .stdout(Stdio::piped())
        .spawn()
        .expect("failed to spawn echo");

    let tr_stdin: Stdio = echo
        .stdout
        .take()
        .unwrap()
        .try_into()
        .expect("failed to convert to Stdio");

    let tr = Command::new("tr")
        .arg("a-z")
        .arg("A-Z")
        .stdin(tr_stdin)
        .stdout(Stdio::piped())
        .spawn()
        .expect("failed to spawn tr");

    let (echo_result, tr_output) = join!(echo.wait(), tr.wait_with_output());

    assert!(echo_result.unwrap().success());

    let tr_output = tr_output.expect("failed to await tr");
    assert!(tr_output.status.success());

    assert_eq!(tr_output.stdout, b"HELLO WORLD!\n");

    Ok(())
}
```

### tokio::process (module) › Caveats

### tokio::process (module) › Dropping/Cancellation

Similar to the behavior to the standard library, and unlike the futures
paradigm of dropping-implies-cancellation, a spawned process will, by
default, continue to execute even after the `Child` handle has been dropped.

The [`Command::kill_on_drop`] method can be used to modify this behavior
and kill the child process if the `Child` wrapper is dropped before it
has exited.

### tokio::process (module) › Unix Processes

On Unix platforms processes must be "reaped" by their parent process after
they have exited in order to release all OS resources. A child process which
has exited, but has not yet been reaped by its parent is considered a "zombie"
process. Such processes continue to count against limits imposed by the system,
and having too many zombie processes present can prevent additional processes
from being spawned.

The tokio runtime will, on a best-effort basis, attempt to reap and clean up
any process which it has spawned. No additional guarantees are made with regard to
how quickly or how often this procedure will take place.

It is recommended to avoid dropping a [`Child`] process handle before it has been
fully `await`ed if stricter cleanup guarantees are required.

[`Command`]: crate::process::Command
[`Command::kill_on_drop`]: crate::process::Command::kill_on_drop
[`Child`]: crate::process::Child

## tokio::runtime (module)

The Tokio runtime.

Unlike other Rust programs, asynchronous applications require runtime
support. In particular, the following runtime services are necessary:

* An **I/O event loop**, called the driver, which drives I/O resources and
  dispatches I/O events to tasks that depend on them.
* A **scheduler** to execute [tasks] that use these I/O resources.
* A **timer** for scheduling work to run after a set period of time.

Tokio's [`Runtime`] bundles all of these services as a single type, allowing
them to be started, shut down, and configured together. However, often it is
not required to configure a [`Runtime`] manually, and a user may just use the
[`tokio::main`] attribute macro, which creates a [`Runtime`] under the hood.

### tokio::runtime (module) › Choose your runtime

Here is the rules of thumb to choose the right runtime for your application.

```plaintext
   +------------------------------------------------------+
   | Do you want work-stealing or multi-thread scheduler? |
   +------------------------------------------------------+
                   | Yes              | No
                   |                  |
                   |                  |
                   v                  |
     +------------------------+       |
     | Multi-threaded Runtime |       |
     +------------------------+       |
                                      |
                                      V
                     +--------------------------------+
                     | Do you execute `!Send` Future? |
                     +--------------------------------+
                           | Yes                 | No
                           |                     |
                           V                     |
                   +---------------+             |
                   | Local Runtime |             |
                   +---------------+             |
                                                 |
                                                 v
                                     +------------------------+
                                     | Current-thread Runtime |
                                     +------------------------+
```

The above decision tree is not exhaustive. there are other factors that
may influence your decision.

### tokio::runtime (module) › Bridging with sync code

See <https://tokio.rs/tokio/topics/bridging> for details.

### tokio::runtime (module) › NUMA awareness

The tokio runtime is not NUMA (Non-Uniform Memory Access) aware.
You may want to start multiple runtimes instead of a single runtime
for better performance on NUMA systems.

### tokio::runtime (module) › Usage

When no fine tuning is required, the [`tokio::main`] attribute macro can be
used.

```no_run
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::net::TcpListener;
use tokio::io::{AsyncReadExt, AsyncWriteExt};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let listener = TcpListener::bind("127.0.0.1:8080").await?;

    loop {
        let (mut socket, _) = listener.accept().await?;

        tokio::spawn(async move {
            let mut buf = [0; 1024];

            // In a loop, read data from the socket and write the data back.
            loop {
                let n = match socket.read(&mut buf).await {
                    // socket closed
                    Ok(0) => return,
                    Ok(n) => n,
                    Err(e) => {
                        println!("failed to read from socket; err = {:?}", e);
                        return;
                    }
                };

                // Write the data back
                if let Err(e) = socket.write_all(&buf[0..n]).await {
                    println!("failed to write to socket; err = {:?}", e);
                    return;
                }
            }
        });
    }
}
# }
```

From within the context of the runtime, additional tasks are spawned using
the [`tokio::spawn`] function. Futures spawned using this function will be
executed on the same thread pool used by the [`Runtime`].

A [`Runtime`] instance can also be used directly.

```no_run
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::net::TcpListener;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::runtime::Runtime;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create the runtime
    let rt  = Runtime::new()?;

    // Spawn the root task
    rt.block_on(async {
        let listener = TcpListener::bind("127.0.0.1:8080").await?;

        loop {
            let (mut socket, _) = listener.accept().await?;

            tokio::spawn(async move {
                let mut buf = [0; 1024];

                // In a loop, read data from the socket and write the data back.
                loop {
                    let n = match socket.read(&mut buf).await {
                        // socket closed
                        Ok(0) => return,
                        Ok(n) => n,
                        Err(e) => {
                            println!("failed to read from socket; err = {:?}", e);
                            return;
                        }
                    };

                    // Write the data back
                    if let Err(e) = socket.write_all(&buf[0..n]).await {
                        println!("failed to write to socket; err = {:?}", e);
                        return;
                    }
                }
            });
        }
    })
}
# }
```

### tokio::runtime (module) › Runtime Configurations

Tokio provides multiple task scheduling strategies, suitable for different
applications. The [runtime builder] or `#[tokio::main]` attribute may be
used to select which scheduler to use.

### tokio::runtime (module) › Multi-Thread Scheduler

The multi-thread scheduler executes futures on a _thread pool_, using a
work-stealing strategy. By default, it will start a worker thread for each
CPU core available on the system. This tends to be the ideal configuration
for most applications. The multi-thread scheduler requires the `rt-multi-thread`
feature flag, and is selected by default:
```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime;

# fn main() -> Result<(), Box<dyn std::error::Error>> {
let threaded_rt = runtime::Runtime::new()?;
# Ok(()) }
# }
```

Most applications should use the multi-thread scheduler, except in some
niche use-cases, such as when running only a single thread is required.

### tokio::runtime (module) › Current-Thread Scheduler

The current-thread scheduler provides a _single-threaded_ future executor.
All tasks will be created and executed on the current thread. This requires
the `rt` feature flag.
```
use tokio::runtime;

# fn main() -> Result<(), Box<dyn std::error::Error>> {
let rt = runtime::Builder::new_current_thread()
    .build()?;
# Ok(()) }
```

### tokio::runtime (module) › Resource drivers

When configuring a runtime by hand, no resource drivers are enabled by
default. In this case, attempting to use networking types or time types will
fail. In order to enable these types, the resource drivers must be enabled.
This is done with [`Builder::enable_io`] and [`Builder::enable_time`]. As a
shorthand, [`Builder::enable_all`] enables both resource drivers.

### tokio::runtime (module) › Driving the runtime

A Tokio runtime can only execute tasks if the runtime is running. Normally
this is not an issue as the default configuration of a runtime is always running,
but alternate configurations such as the current-thread runtime require that
[`Runtime::block_on`] is called.

- A multi-threaded runtime is always running because it spawns its own worker
  threads.
- A current-thread runtime does not spawn any worker threads, so it can only
  execute tasks when you provide a thread by calling [`Runtime::block_on`].
- A [`LocalSet`](crate::task::LocalSet) only executes local tasks spawned on
  it when the `LocalSet` is `.awaited` or otherwise driven using one of its
  methods for this purpose.

Please be aware that [`Handle::block_on`] does not drive the runtime.
There must be at least one call to [`Runtime::block_on`] when using the current
thread runtime. [`Handle::block_on`] is not enough.

### tokio::runtime (module) › Lifetime of spawned threads

The runtime may spawn threads depending on its configuration and usage. The
multi-thread scheduler spawns threads to schedule tasks and for `spawn_blocking`
calls.

While the `Runtime` is active, threads may shut down after periods of being
idle. Once `Runtime` is dropped, all runtime threads have usually been
terminated, but in the presence of unstoppable spawned work are not
guaranteed to have been terminated. See the
[struct level documentation](Runtime#shutdown) for more details.

### tokio::runtime (module) › Unix `fork`

User code that calls `fork(2)` without immediately calling `exec` must not
reuse Tokio in the child process. Tokio supports this kind of fork only in
two cases:

- The fork happens before the parent process has used Tokio in any way.
- The child process does not use Tokio after the fork.

Creating or using a Tokio runtime in a child process after the parent has
used Tokio is not supported, even if the runtime in the child is newly
created. Some Tokio modules, including process and signal handling, use
process-global state that cannot currently be reset after `fork`.

[tasks]: crate::task
[`Runtime`]: Runtime
[`tokio::spawn`]: crate::spawn
[`tokio::main`]: ../attr.main.html
[runtime builder]: crate::runtime::Builder
[`Runtime::new`]: crate::runtime::Runtime::new
[`Builder::enable_io`]: crate::runtime::Builder::enable_io
[`Builder::enable_time`]: crate::runtime::Builder::enable_time
[`Builder::enable_all`]: crate::runtime::Builder::enable_all

### tokio::runtime (module) › Detailed runtime behavior

This section gives more details into how the Tokio runtime will schedule
tasks for execution.

At its most basic level, a runtime has a collection of tasks that need to be
scheduled. It will repeatedly remove a task from that collection and
schedule it (by calling [`poll`]). When the collection is empty, the thread
will go to sleep until a task is added to the collection.

However, the above is not sufficient to guarantee a well-behaved runtime.
For example, the runtime might have a single task that is always ready to be
scheduled, and schedule that task every time. This is a problem because it
starves other tasks by not scheduling them. To solve this, Tokio provides
the following fairness guarantee:

> If the total number of tasks does not grow without bound, and no task is
> [blocking the thread], then it is guaranteed that tasks are scheduled
> fairly.

Or, more formally:

> Under the following two assumptions:
>
> * There is some number `MAX_TASKS` such that the total number of tasks on
>   the runtime at any specific point in time never exceeds `MAX_TASKS`.
> * There is some number `MAX_SCHEDULE` such that calling [`poll`] on any
>   task spawned on the runtime returns within `MAX_SCHEDULE` time units.
>
> Then, there is some number `MAX_DELAY` such that when a task is woken, it
> will be scheduled by the runtime within `MAX_DELAY` time units.

(Here, `MAX_TASKS` and `MAX_SCHEDULE` can be any number and the user of
the runtime may choose them. The `MAX_DELAY` number is controlled by the
runtime, and depends on the value of `MAX_TASKS` and `MAX_SCHEDULE`.)

Other than the above fairness guarantee, there is no guarantee about the
order in which tasks are scheduled. There is also no guarantee that the
runtime is equally fair to all tasks. For example, if the runtime has two
tasks A and B that are both ready, then the runtime may schedule A five
times before it schedules B. This is the case even if A yields using
[`yield_now`]. All that is guaranteed is that it will schedule B eventually.

Normally, tasks are scheduled only if they have been woken by calling
[`wake`] on their waker. However, this is not guaranteed, and Tokio may
schedule tasks that have not been woken under some circumstances. This is
called a spurious wakeup.

### tokio::runtime (module) › IO and timers

Beyond just scheduling tasks, the runtime must also manage IO resources and
timers. It does this by periodically checking whether there are any IO
resources or timers that are ready, and waking the relevant task so that
it will be scheduled.

These checks are performed periodically between scheduling tasks. Under the
same assumptions as the previous fairness guarantee, Tokio guarantees that
it will wake tasks with an IO or timer event within some maximum number of
time units.

### tokio::runtime (module) › Current thread runtime (behavior at the time of writing)

This section describes how the [current thread runtime] behaves today. This
behavior may change in future versions of Tokio.

The current thread runtime maintains two FIFO queues of tasks that are ready
to be scheduled: the global queue and the local queue. The runtime will prefer
to choose the next task to schedule from the local queue, and will only pick a
task from the global queue if the local queue is empty, or if it has picked
a task from the local queue 31 times in a row. The number 31 can be
changed using the [`global_queue_interval`] setting.

The runtime will check for new IO or timer events whenever there are no
tasks ready to be scheduled, or when it has scheduled 61 tasks in a row. The
number 61 may be changed using the [`event_interval`] setting.

When a task is woken from within a task running on the runtime, then the
woken task is added directly to the local queue. Otherwise, the task is
added to the global queue. The current thread runtime does not use [the lifo
slot optimization].

### tokio::runtime (module) › Multi threaded runtime (behavior at the time of writing)

This section describes how the [multi thread runtime] behaves today. This
behavior may change in future versions of Tokio.

A multi thread runtime has a fixed number of worker threads, which are all
created on startup. The multi thread runtime maintains one global queue, and
a local queue for each worker thread. The local queue of a worker thread can
fit at most 256 tasks. If more than 256 tasks are added to the local queue,
then half of them are moved to the global queue to make space.

The runtime will prefer to choose the next task to schedule from the local
queue, and will only pick a task from the global queue if the local queue is
empty, or if it has picked a task from the local queue
[`global_queue_interval`] times in a row. If the value of
[`global_queue_interval`] is not explicitly set using the runtime builder,
then the runtime will dynamically compute it using a heuristic that targets
10ms intervals between each check of the global queue (based on the
[`worker_mean_poll_time`] metric).

If both the local queue and global queue is empty, then the worker thread
will attempt to steal tasks from the local queue of another worker thread.
Stealing is done by moving half of the tasks in one local queue to another
local queue.

The runtime will check for new IO or timer events whenever there are no
tasks ready to be scheduled, or when it has scheduled 61 tasks in a row. The
number 61 may be changed using the [`event_interval`] setting.

The multi thread runtime uses [the lifo slot optimization]: Whenever a task
wakes up another task, the other task is added to the worker thread's lifo
slot instead of being added to a queue. If there was already a task in the
lifo slot when this happened, then the lifo slot is replaced, and the task
that used to be in the lifo slot is placed in the thread's local queue.
When the runtime finishes scheduling a task, it will schedule the task in
the lifo slot immediately, if any. When the lifo slot is used, the [coop
budget] is not reset. Furthermore, if a worker thread uses the lifo slot
three times in a row, it is temporarily disabled until the worker thread has
scheduled a task that didn't come from the lifo slot. The lifo slot can be
disabled using the [`disable_lifo_slot`] setting. The lifo slot is separate
from the local queue, so other worker threads cannot steal the task in the
lifo slot.

When a task is woken from a thread that is not a worker thread, then the
task is placed in the global queue.

### tokio::runtime (module) › Performance tuning

### tokio::runtime (module) › File descriptor table pre-warming

On Linux, file descriptor table growth can stall worker threads. See the
[`prewarm-fd-table`] example.

[`poll`]: std::future::Future::poll
[`wake`]: std::task::Waker::wake
[`yield_now`]: crate::task::yield_now
[blocking the thread]: https://ryhl.io/blog/async-what-is-blocking/
[current thread runtime]: crate::runtime::Builder::new_current_thread
[multi thread runtime]: crate::runtime::Builder::new_multi_thread
[`global_queue_interval`]: crate::runtime::Builder::global_queue_interval
[`event_interval`]: crate::runtime::Builder::event_interval
[`disable_lifo_slot`]: crate::runtime::Builder::disable_lifo_slot
[the lifo slot optimization]: crate::runtime::Builder::disable_lifo_slot
[coop budget]: crate::task::coop#cooperative-scheduling
[`worker_mean_poll_time`]: crate::runtime::RuntimeMetrics::worker_mean_poll_time
[`prewarm-fd-table`]: https://github.com/tokio-rs/tokio/blob/master/examples/prewarm-fd-table.rs

## tokio::runtime::dump (module)

Snapshots of runtime state.

See [`Handle::dump`][crate::runtime::Handle::dump].

## tokio::signal (module)

Asynchronous signal handling for Tokio.

Note that signal handling is in general a very tricky topic and should be
used with great care. This crate attempts to implement 'best practice' for
signal handling, but it should be evaluated for your own applications' needs
to see if it's suitable.

There are some fundamental limitations of this crate documented on the OS
specific structures, as well.

### tokio::signal (module) › Examples

Print on "ctrl-c" notification.

```rust,no_run
use tokio::signal;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    signal::ctrl_c().await?;
    println!("ctrl-c received!");
    Ok(())
}
```

Wait for `SIGHUP` on Unix

```rust,no_run
# #[cfg(unix)] {
use tokio::signal::unix::{signal, SignalKind};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // An infinite stream of hangup signals.
    let mut stream = signal(SignalKind::hangup())?;

    // Print whenever a HUP signal is received
    loop {
        stream.recv().await;
        println!("got signal HUP");
    }
}
# }
```

## tokio::signal::unix (module)

Unix-specific types for signal handling.

This module is only defined on Unix platforms and contains the primary
`Signal` type for receiving notifications of signals.

## tokio::signal::windows (module)

Windows-specific types for signal handling.

This module is only defined on Windows and allows receiving "ctrl-c",
"ctrl-break", "ctrl-logoff", "ctrl-shutdown", and "ctrl-close"
notifications. These events are listened for via the `SetConsoleCtrlHandler`
function which receives the corresponding `windows_sys` event type.

## tokio::stream (module)

Due to the `Stream` trait's inclusion in `std` landing later than Tokio's 1.0
release, most of the Tokio stream utilities have been moved into the [`tokio-stream`]
crate.

### tokio::stream (module) › Why was `Stream` not included in Tokio 1.0?

Originally, we had planned to ship Tokio 1.0 with a stable `Stream` type
but unfortunately the [RFC] had not been merged in time for `Stream` to
reach `std` on a stable compiler in time for the 1.0 release of Tokio. For
this reason, the team has decided to move all `Stream` based utilities to
the [`tokio-stream`] crate. While this is not ideal, once `Stream` has made
it into the standard library and the `MSRV` period has passed, we will implement
stream for our different types.

While this may seem unfortunate, not all is lost as you can get much of the
`Stream` support with `async/await` and `while let` loops. It is also possible
to create a `impl Stream` from `async fn` using the [`async-stream`] crate.

[`tokio-stream`]: https://docs.rs/tokio-stream
[`async-stream`]: https://docs.rs/async-stream
[RFC]: https://github.com/rust-lang/rfcs/pull/2996

### tokio::stream (module) › Example

Convert a [`sync::mpsc::Receiver`] to an `impl Stream`.

```rust,no_run
use tokio::sync::mpsc;

let (tx, mut rx) = mpsc::channel::<usize>(16);

let stream = async_stream::stream! {
    while let Some(item) = rx.recv().await {
        yield item;
    }
};
```

## tokio::sync (module)

Synchronization primitives for use in asynchronous contexts.

Tokio programs tend to be organized as a set of [tasks] where each task
operates independently and may be executed on separate physical threads. The
synchronization primitives provided in this module permit these independent
tasks to communicate together.

[tasks]: crate::task

### tokio::sync (module) › Message passing

The most common form of synchronization in a Tokio program is message
passing. Two tasks operate independently and send messages to each other to
synchronize. Doing so has the advantage of avoiding shared state.

Message passing is implemented using channels. A channel supports sending a
message from one producer task to one or more consumer tasks. There are a
few flavors of channels provided by Tokio. Each channel flavor supports
different message passing patterns. When a channel supports multiple
producers, many separate tasks may **send** messages. When a channel
supports multiple consumers, many different separate tasks may **receive**
messages.

Tokio provides many different channel flavors as different message passing
patterns are best handled with different implementations.

### tokio::sync (module) › `oneshot` channel

The [`oneshot` channel][oneshot] supports sending a **single** value from a
single producer to a single consumer. This channel is usually used to send
the result of a computation to a waiter.

**Example:** using a [`oneshot` channel][oneshot] to receive the result of a
computation.

```
use tokio::sync::oneshot;

async fn some_computation() -> String {
    "represents the result of the computation".to_string()
}

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, rx) = oneshot::channel();

tokio::spawn(async move {
    let res = some_computation().await;
    tx.send(res).unwrap();
});

// Do other work while the computation is happening in the background

// Wait for the computation result
let res = rx.await.unwrap();
# }
```

Note, if the task produces a computation result as its final
action before terminating, the [`JoinHandle`] can be used to
receive that value instead of allocating resources for the
`oneshot` channel. Awaiting on [`JoinHandle`] returns `Result`. If
the task panics, the `Joinhandle` yields `Err` with the panic
cause.

**Example:**

```
async fn some_computation() -> String {
    "the result of the computation".to_string()
}

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let join_handle = tokio::spawn(async move {
    some_computation().await
});

// Do other work while the computation is happening in the background

// Wait for the computation result
let res = join_handle.await.unwrap();
# }
```

[`JoinHandle`]: crate::task::JoinHandle

### tokio::sync (module) › `mpsc` channel

The [`mpsc` channel][mpsc] supports sending **many** values from **many**
producers to a single consumer. This channel is often used to send work to a
task or to receive the result of many computations.

This is also the channel you should use if you want to send many messages
from a single producer to a single consumer. There is no dedicated spsc
channel.

**Example:** using an mpsc to incrementally stream the results of a series
of computations.

```
use tokio::sync::mpsc;

async fn some_computation(input: u32) -> String {
    format!("the result of computation {}", input)
}

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = mpsc::channel(100);

tokio::spawn(async move {
    for i in 0..10 {
        let res = some_computation(i).await;
        tx.send(res).await.unwrap();
    }
});

while let Some(res) = rx.recv().await {
    println!("got = {}", res);
}
# }
```

The argument to `mpsc::channel` is the channel capacity. This is the maximum
number of values that can be stored in the channel pending receipt at any
given time. Properly setting this value is key in implementing robust
programs as the channel capacity plays a critical part in handling back
pressure.

A common concurrency pattern for resource management is to spawn a task
dedicated to managing that resource and using message passing between other
tasks to interact with the resource. The resource may be anything that may
not be concurrently used. Some examples include a socket and program state.
For example, if multiple tasks need to send data over a single socket, spawn
a task to manage the socket and use a channel to synchronize.

**Example:** sending data from many tasks over a single socket using message
passing.

```no_run
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::io::{self, AsyncWriteExt};
use tokio::net::TcpStream;
use tokio::sync::mpsc;

#[tokio::main]
async fn main() -> io::Result<()> {
    let mut socket = TcpStream::connect("www.example.com:1234").await?;
    let (tx, mut rx) = mpsc::channel(100);

    for _ in 0..10 {
        // Each task needs its own `tx` handle. This is done by cloning the
        // original handle.
        let tx = tx.clone();

        tokio::spawn(async move {
            tx.send(&b"data to write"[..]).await.unwrap();
        });
    }

    // The `rx` half of the channel returns `None` once **all** `tx` clones
    // drop. To ensure `None` is returned, drop the handle owned by the
    // current task. If this `tx` handle is not dropped, there will always
    // be a single outstanding `tx` handle.
    drop(tx);

    while let Some(res) = rx.recv().await {
        socket.write_all(res).await?;
    }

    Ok(())
}
# }
```

The [`mpsc`] and [`oneshot`] channels can be combined to provide a request /
response type synchronization pattern with a shared resource. A task is
spawned to synchronize a resource and waits on commands received on a
[`mpsc`] channel. Each command includes a [`oneshot`] `Sender` on which the
result of the command is sent.

**Example:** use a task to synchronize a `u64` counter. Each task sends an
"fetch and increment" command. The counter value **before** the increment is
sent over the provided `oneshot` channel.

```
use tokio::sync::{oneshot, mpsc};
use Command::Increment;

enum Command {
    Increment,
    // Other commands can be added here
}

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (cmd_tx, mut cmd_rx) = mpsc::channel::<(Command, oneshot::Sender<u64>)>(100);

// Spawn a task to manage the counter
tokio::spawn(async move {
    let mut counter: u64 = 0;

    while let Some((cmd, response)) = cmd_rx.recv().await {
        match cmd {
            Increment => {
                let prev = counter;
                counter += 1;
                response.send(prev).unwrap();
            }
        }
    }
});

let mut join_handles = vec![];

// Spawn tasks that will send the increment command.
for _ in 0..10 {
    let cmd_tx = cmd_tx.clone();

    join_handles.push(tokio::spawn(async move {
        let (resp_tx, resp_rx) = oneshot::channel();

        cmd_tx.send((Increment, resp_tx)).await.ok().unwrap();
        let res = resp_rx.await.unwrap();

        println!("previous value = {}", res);
    }));
}

// Wait for all tasks to complete
for join_handle in join_handles.drain(..) {
    join_handle.await.unwrap();
}
# }
```

### tokio::sync (module) › `broadcast` channel

The [`broadcast` channel] supports sending **many** values from
**many** producers to **many** consumers. Each consumer will receive
**each** value. This channel can be used to implement "fan out" style
patterns common with pub / sub or "chat" systems.

This channel tends to be used less often than `oneshot` and `mpsc` but still
has its use cases.

This is also the channel you should use if you want to broadcast values from
a single producer to many consumers. There is no dedicated spmc broadcast
channel.

Basic usage

```
use tokio::sync::broadcast;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx1) = broadcast::channel(16);
let mut rx2 = tx.subscribe();

tokio::spawn(async move {
    assert_eq!(rx1.recv().await.unwrap(), 10);
    assert_eq!(rx1.recv().await.unwrap(), 20);
});

tokio::spawn(async move {
    assert_eq!(rx2.recv().await.unwrap(), 10);
    assert_eq!(rx2.recv().await.unwrap(), 20);
});

tx.send(10).unwrap();
tx.send(20).unwrap();
# }
```

[`broadcast` channel]: crate::sync::broadcast

### tokio::sync (module) › `watch` channel

The [`watch` channel] supports sending **many** values from **many**
producers to **many** consumers. However, only the **most recent** value is
stored in the channel. Consumers are notified when a new value is sent, but
there is no guarantee that consumers will see **all** values.

The [`watch` channel] is similar to a [`broadcast` channel] with capacity 1.

Use cases for the [`watch` channel] include broadcasting configuration
changes or signalling program state changes, such as transitioning to
shutdown.

**Example:** use a [`watch` channel] to notify tasks of configuration
changes. In this example, a configuration file is checked periodically. When
the file changes, the configuration changes are signalled to consumers.

```
use tokio::sync::watch;
use tokio::time::{self, Duration, Instant};

use std::io;

#[derive(Debug, Clone, Eq, PartialEq)]
struct Config {
    timeout: Duration,
}

impl Config {
    async fn load_from_file() -> io::Result<Config> {
        // file loading and deserialization logic here
# Ok(Config { timeout: Duration::from_secs(1) })
    }
}

async fn my_async_operation() {
    // Do something here
}

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
// Load initial configuration value
let mut config = Config::load_from_file().await.unwrap();

// Create the watch channel, initialized with the loaded configuration
let (tx, rx) = watch::channel(config.clone());

// Spawn a task to monitor the file.
tokio::spawn(async move {
    loop {
        // Wait 10 seconds between checks
        time::sleep(Duration::from_secs(10)).await;

        // Load the configuration file
        let new_config = Config::load_from_file().await.unwrap();

        // If the configuration changed, send the new config value
        // on the watch channel.
        if new_config != config {
            tx.send(new_config.clone()).unwrap();
            config = new_config;
        }
    }
});

let mut handles = vec![];

// Spawn tasks that runs the async operation for at most `timeout`. If
// the timeout elapses, restart the operation.
//
// The task simultaneously watches the `Config` for changes. When the
// timeout duration changes, the timeout is updated without restarting
// the in-flight operation.
for _ in 0..5 {
    // Clone a config watch handle for use in this task
    let mut rx = rx.clone();

    let handle = tokio::spawn(async move {
        // Start the initial operation and pin the future to the stack.
        // Pinning to the stack is required to resume the operation
        // across multiple calls to `select!`
        let op = my_async_operation();
        tokio::pin!(op);

        // Get the initial config value
        let mut conf = rx.borrow().clone();

        let mut op_start = Instant::now();
        let sleep = time::sleep_until(op_start + conf.timeout);
        tokio::pin!(sleep);

        loop {
            tokio::select! {
                _ = &mut sleep => {
                    // The operation elapsed. Restart it
                    op.set(my_async_operation());

                    // Track the new start time
                    op_start = Instant::now();

                    // Restart the timeout
                    sleep.set(time::sleep_until(op_start + conf.timeout));
                }
                _ = rx.changed() => {
                    conf = rx.borrow_and_update().clone();

                    // The configuration has been updated. Update the
                    // `sleep` using the new `timeout` value.
                    sleep.as_mut().reset(op_start + conf.timeout);
                }
                _ = &mut op => {
                    // The operation completed!
                    return
                }
            }
        }
    });

    handles.push(handle);
}

for handle in handles.drain(..) {
    handle.await.unwrap();
}
# }
```

[`watch` channel]: mod@crate::sync::watch
[`broadcast` channel]: mod@crate::sync::broadcast

### tokio::sync (module) › State synchronization

The remaining synchronization primitives focus on synchronizing state.
These are asynchronous equivalents to versions provided by `std`. They
operate in a similar way as their `std` counterparts but will wait
asynchronously instead of blocking the thread.

* [`Barrier`] Ensures multiple tasks will wait for each other to reach a
  point in the program, before continuing execution all together.

* [`Mutex`] Mutual Exclusion mechanism, which ensures that at most one
  thread at a time is able to access some data.

* [`Notify`] Basic task notification. `Notify` supports notifying a
  receiving task without sending data. In this case, the task wakes up and
  resumes processing.

* [`RwLock`] Provides a mutual exclusion mechanism which allows multiple
  readers at the same time, while allowing only one writer at a time. In
  some cases, this can be more efficient than a mutex.

* [`Semaphore`] Limits the amount of concurrency. A semaphore holds a
  number of permits, which tasks may request in order to enter a critical
  section. Semaphores are useful for implementing limiting or bounding of
  any kind.

### tokio::sync (module) › Runtime compatibility

All synchronization primitives provided in this module are runtime agnostic.
You can freely move them between different instances of the Tokio runtime
or even use them from non-Tokio runtimes.

When used in a Tokio runtime, the synchronization primitives participate in
[cooperative scheduling](crate::task::coop#cooperative-scheduling) to avoid
starvation. This feature does not apply when used from non-Tokio runtimes.

As an exception, methods ending in `_timeout` are not runtime agnostic
because they require access to the Tokio timer. See the documentation of
each `*_timeout` method for more information on its use.

## tokio::sync::broadcast (module)

A multi-producer, multi-consumer broadcast queue. Each sent value is seen by
all consumers.

A [`Sender`] is used to broadcast values to **all** connected [`Receiver`]
values. [`Sender`] handles are clone-able, allowing concurrent send and
receive actions. [`Sender`] and [`Receiver`] are both `Send` and `Sync` as
long as `T` is `Send`.

When a value is sent, **all** [`Receiver`] handles are notified and will
receive the value. The value is stored once inside the channel and cloned on
demand for each receiver. Once all receivers have received a clone of the
value, the value is released from the channel.

A channel is created by calling [`channel`], specifying the maximum number
of messages the channel can retain at any given time.

New [`Receiver`] handles are created by calling [`Sender::subscribe`]. The
returned [`Receiver`] will receive values sent **after** the call to
`subscribe`.

This channel is also suitable for the single-producer multi-consumer
use-case, where a single sender broadcasts values to many receivers.

### tokio::sync::broadcast (module) › Lagging

As sent messages must be retained until **all** [`Receiver`] handles receive
a clone, broadcast channels are susceptible to the "slow receiver" problem.
In this case, all but one receiver are able to receive values at the rate
they are sent. Because one receiver is stalled, the channel starts to fill
up.

This broadcast channel implementation handles this case by setting a hard
upper bound on the number of values the channel may retain at any given
time. This upper bound is passed to the [`channel`] function as an argument.
The provided capacity is rounded **up** to the next power of two; that
rounded size is the number of messages the ring buffer can hold, and is what
lag detection is based on. For example, `channel(3)` allocates a buffer of
length 4, so a receiver only lags once it falls more than 4 messages behind
the sender.

If a value is sent when the channel is at capacity, the oldest value
currently held by the channel is overwritten. This frees up space for the
new value. Any receiver that has not yet seen the overwritten value will
return [`RecvError::Lagged`] the next time [`recv`] (or
[`try_recv`](Receiver::try_recv)) is called. The error carries the number of
messages that were dropped before the receiver's cursor and are therefore
no longer available.

Returning [`RecvError::Lagged`] does **not** close or disconnect the
receiver. The lagging receiver's internal cursor is advanced to the oldest
value still retained by the channel. The **next** successful call to
[`recv`] / [`try_recv`](Receiver::try_recv) returns that oldest retained
value (unless further sends overwrite it again before the receiver reads
it). Subsequent receives then continue in send order from there.

This behavior enables a receiver to detect when it has lagged so far behind
that data has been dropped. The caller may decide how to respond to this:
either by aborting its task or by tolerating lost messages and resuming
consumption of the channel.

### tokio::sync::broadcast (module) › Closing

When **all** [`Sender`] handles have been dropped, no new values may be
sent. At this point, the channel is "closed". Once a receiver has received
all values retained by the channel, the next call to [`recv`] will return
with [`RecvError::Closed`].

When a [`Receiver`] handle is dropped, any messages not read by the receiver
will be marked as read. If this receiver was the only one not to have read
that message, the message will be dropped at this point.

[`Sender`]: crate::sync::broadcast::Sender
[`Sender::subscribe`]: crate::sync::broadcast::Sender::subscribe
[`Receiver`]: crate::sync::broadcast::Receiver
[`channel`]: crate::sync::broadcast::channel
[`RecvError::Lagged`]: crate::sync::broadcast::error::RecvError::Lagged
[`RecvError::Closed`]: crate::sync::broadcast::error::RecvError::Closed
[`recv`]: crate::sync::broadcast::Receiver::recv

### tokio::sync::broadcast (module) › Examples

Basic usage

```
use tokio::sync::broadcast;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx1) = broadcast::channel(16);
let mut rx2 = tx.subscribe();

tokio::spawn(async move {
    assert_eq!(rx1.recv().await.unwrap(), 10);
    assert_eq!(rx1.recv().await.unwrap(), 20);
});

tokio::spawn(async move {
    assert_eq!(rx2.recv().await.unwrap(), 10);
    assert_eq!(rx2.recv().await.unwrap(), 20);
});

tx.send(10).unwrap();
tx.send(20).unwrap();
# }
```

Handling lag

```
use tokio::sync::broadcast;
use tokio::sync::broadcast::error::RecvError;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
// Capacity 2 → ring buffer of length 2.
let (tx, mut rx) = broadcast::channel(2);

tx.send(10).unwrap();
tx.send(20).unwrap();
// Overwrites 10; receiver has not read it yet.
tx.send(30).unwrap();

// One message (10) was dropped; cursor moves to the oldest retained value (20).
assert!(matches!(rx.recv().await, Err(RecvError::Lagged(1))));

// At this point, we can abort or continue with lost messages.
// Continuing resumes from the oldest retained message.
assert_eq!(20, rx.recv().await.unwrap());
assert_eq!(30, rx.recv().await.unwrap());
# }
```

## tokio::sync::broadcast::error (module)

Broadcast error types

## tokio::sync::futures (module)

Named future types.

## tokio::sync::mpsc (module)

A multi-producer, single-consumer queue for sending values between
asynchronous tasks.

This module provides two variants of the channel: bounded and unbounded. The
bounded variant has a limit on the number of messages that the channel can
store, and if this limit is reached, trying to send another message will
wait until a message is received from the channel. An unbounded channel has
an infinite capacity, so the `send` method will always complete immediately.
This makes the [`UnboundedSender`] usable from both synchronous and
asynchronous code.

Similar to the `mpsc` channels provided by `std`, the channel constructor
functions provide separate send and receive handles, [`Sender`] and
[`Receiver`] for the bounded channel, [`UnboundedSender`] and
[`UnboundedReceiver`] for the unbounded channel. If there is no message to read,
the current task will be notified when a new value is sent. [`Sender`] and
[`UnboundedSender`] allow sending values into the channel. If the bounded
channel is at capacity, the send is rejected and the task will be notified
when additional capacity is available. In other words, the channel provides
backpressure.

This channel is also suitable for the single-producer single-consumer
use-case. (Unless you only need to send one message, in which case you
should use the [oneshot] channel.)

### tokio::sync::mpsc (module) › Disconnection

When all [`Sender`] handles have been dropped, it is no longer
possible to send values into the channel. This is considered the termination
event of the stream. Once all senders have been dropped and any remaining
buffered values have been received, `Receiver::recv` returns `None`
(and `Receiver::poll_recv` returns `Poll::Ready(None)`).

If the [`Receiver`] handle is dropped, then messages can no longer
be read out of the channel. In this case, all further attempts to send will
result in an error. Additionally, all unread messages will be drained from the
channel and dropped.

### tokio::sync::mpsc (module) › Clean Shutdown

When the [`Receiver`] is dropped, it is possible for unprocessed messages to
remain in the channel. Instead, it is usually desirable to perform a "clean"
shutdown. To do this, the receiver first calls `close`, which will prevent
any further messages to be sent into the channel. Then, the receiver
consumes the channel to completion, at which point the receiver can be
dropped.

### tokio::sync::mpsc (module) › Communicating between sync and async code

When you want to communicate between synchronous and asynchronous code, there
are two situations to consider:

**Bounded channel**: If you need a bounded channel, you should use a bounded
Tokio `mpsc` channel for both directions of communication. Instead of calling
the async [`send`][bounded-send] or [`recv`][bounded-recv] methods, in
synchronous code you will need to use the [`blocking_send`][blocking-send] or
[`blocking_recv`][blocking-recv] methods.

**Unbounded channel**: You should use the kind of channel that matches where
the receiver is. So for sending a message _from async to sync_, you should
use [the standard library unbounded channel][std-unbounded] or
[crossbeam][crossbeam-unbounded].  Similarly, for sending a message _from sync
to async_, you should use an unbounded Tokio `mpsc` channel.

Please be aware that the above remarks were written with the `mpsc` channel
in mind, but they can also be generalized to other kinds of channels. In
general, any channel method that isn't marked async can be called anywhere,
including outside of the runtime. For example, sending a message on a
[oneshot] channel from outside the runtime is perfectly fine.

### tokio::sync::mpsc (module) › Multiple runtimes

The `mpsc` channel is runtime agnostic. You can freely move it between
different instances of the Tokio runtime or even use it from non-Tokio
runtimes.

When used in a Tokio runtime, it participates in
[cooperative scheduling](crate::task::coop#cooperative-scheduling) to avoid
starvation. This feature does not apply when used from non-Tokio runtimes.

As an exception, methods ending in `_timeout` are not runtime agnostic
because they require access to the Tokio timer. See the documentation of
each `*_timeout` method for more information on its use.

### tokio::sync::mpsc (module) › Allocation behavior

<div class="warning">The implementation details described in this section may change in future
Tokio releases.</div>

The mpsc channel stores elements in blocks. Blocks are organized in a linked list. Sending
pushes new elements onto the block at the front of the list, and receiving pops them off the
one at the back. A block can hold 32 messages on a 64-bit target and 16 messages on a 32-bit
target. This number is independent of channel and message size. Each block also stores 4
pointer-sized values for bookkeeping (so on a 64-bit machine, each message has 1 byte of
overhead).

When all values in a block have been received, it becomes empty. It will then be freed, unless
the channel's first block (where newly-sent elements are being stored) has no next block. In
that case, the empty block is reused as the next block.

[`Sender`]: crate::sync::mpsc::Sender
[`Receiver`]: crate::sync::mpsc::Receiver
[bounded-send]: crate::sync::mpsc::Sender::send()
[bounded-recv]: crate::sync::mpsc::Receiver::recv()
[blocking-send]: crate::sync::mpsc::Sender::blocking_send()
[blocking-recv]: crate::sync::mpsc::Receiver::blocking_recv()
[`UnboundedSender`]: crate::sync::mpsc::UnboundedSender
[`UnboundedReceiver`]: crate::sync::mpsc::UnboundedReceiver
[oneshot]: crate::sync::oneshot
[`Handle::block_on`]: crate::runtime::Handle::block_on()
[std-unbounded]: std::sync::mpsc::channel
[crossbeam-unbounded]: https://docs.rs/crossbeam/*/crossbeam/channel/fn.unbounded.html
[`send_timeout`]: crate::sync::mpsc::Sender::send_timeout

## tokio::sync::mpsc::error (module)

Channel error types.

## tokio::sync::oneshot (module)

A one-shot channel is used for sending a single message between
asynchronous tasks. The [`channel`] function is used to create a
[`Sender`] and [`Receiver`] handle pair that form the channel.

The `Sender` handle is used by the producer to send the value.
The `Receiver` handle is used by the consumer to receive the value.

Each handle can be used on separate tasks.

Since the `send` method is not async, it can be used anywhere. This includes
sending between two runtimes, and using it from non-async code.

If the [`Receiver`] is closed before receiving a message which has already
been sent, the message will remain in the channel until the receiver is
dropped, at which point the message will be dropped immediately.

### tokio::sync::oneshot (module) › Examples

```
use tokio::sync::oneshot;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, rx) = oneshot::channel();

tokio::spawn(async move {
    if let Err(_) = tx.send(3) {
        println!("the receiver dropped");
    }
});

match rx.await {
    Ok(v) => println!("got = {:?}", v),
    Err(_) => println!("the sender dropped"),
}
# }
```

If the sender is dropped without sending, the receiver will fail with
[`error::RecvError`]:

```
use tokio::sync::oneshot;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, rx) = oneshot::channel::<u32>();

tokio::spawn(async move {
    drop(tx);
});

match rx.await {
    Ok(_) => panic!("This doesn't happen"),
    Err(_) => println!("the sender dropped"),
}
# }
```

To use a `oneshot` channel in a `tokio::select!` loop, add `&mut` in front of
the channel.

```
use tokio::sync::oneshot;
use tokio::time::{interval, sleep, Duration};

# #[tokio::main(flavor = "current_thread")]
# async fn _doc() {}
# #[tokio::main(flavor = "current_thread", start_paused = true)]
# async fn main() {
let (send, mut recv) = oneshot::channel();
let mut interval = interval(Duration::from_millis(100));

# let handle =
tokio::spawn(async move {
    sleep(Duration::from_secs(1)).await;
    send.send("shut down").unwrap();
});

loop {
    tokio::select! {
        _ = interval.tick() => println!("Another 100ms"),
        msg = &mut recv => {
            println!("Got message: {}", msg.unwrap());
            break;
        }
    }
}
# handle.await.unwrap();
# }
```

To use a `Sender` from a destructor, put it in an [`Option`] and call
[`Option::take`].

```
use tokio::sync::oneshot;

struct SendOnDrop {
    sender: Option<oneshot::Sender<&'static str>>,
}
impl Drop for SendOnDrop {
    fn drop(&mut self) {
        if let Some(sender) = self.sender.take() {
            // Using `let _ =` to ignore send errors.
            let _ = sender.send("I got dropped!");
        }
    }
}

# #[tokio::main(flavor = "current_thread")]
# async fn _doc() {}
# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (send, recv) = oneshot::channel();

let send_on_drop = SendOnDrop { sender: Some(send) };
drop(send_on_drop);

assert_eq!(recv.await, Ok("I got dropped!"));
# }
```

## tokio::sync::oneshot::error (module)

`Oneshot` error types.

## tokio::sync::watch (module)

A multi-producer, multi-consumer channel that only retains the *last* sent
value.

This channel is useful for watching for changes to a value from multiple
points in the code base, for example, changes to configuration values.

### tokio::sync::watch (module) › Usage

[`channel`] returns a [`Sender`] / [`Receiver`] pair. These are the producer
and consumer halves of the channel. The channel is created with an initial
value.

Each [`Receiver`] independently tracks the last value *seen* by its caller.

To access the **current** value stored in the channel and mark it as *seen*
by a given [`Receiver`], use [`Receiver::borrow_and_update()`].

To access the current value **without** marking it as *seen*, use
[`Receiver::borrow()`]. (If the value has already been marked *seen*,
[`Receiver::borrow()`] is equivalent to [`Receiver::borrow_and_update()`].)

For more information on when to use these methods, see
[here](#borrow_and_update-versus-borrow).

### tokio::sync::watch (module) › Change notifications

The [`Receiver`] half provides an asynchronous [`changed`] method. This
method is ready when a new, *unseen* value is sent via the [`Sender`] half.

* [`Receiver::changed()`] returns:
    * `Ok(())` on receiving a new value.
    * `Err(`[`RecvError`](error::RecvError)`)` if the
      channel has been closed __AND__ the current value is *seen*.
* If the current value is *unseen* when calling [`changed`], then
  [`changed`] will return immediately. If the current value is *seen*, then
  it will sleep until either a new message is sent via the [`Sender`] half,
  or the [`Sender`] is dropped.
* On completion, the [`changed`] method marks the new value as *seen*.
* At creation, the initial value is considered *seen*. In other words,
  [`Receiver::changed()`] will not return until a subsequent value is sent.
* New [`Receiver`] instances can be created with [`Sender::subscribe()`].
  The current value at the time the [`Receiver`] is created is considered
  *seen*.

### tokio::sync::watch (module) › [`changed`] versus [`has_changed`]

The [`Receiver`] half provides two methods for checking for changes
in the channel, [`has_changed`] and [`changed`].

* [`has_changed`] is a *synchronous* method that checks whether the current
  value is seen or not and returns a boolean. This method does __not__ mark the
  value as seen.

* [`changed`] is an *asynchronous* method that will return once an unseen
  value is in the channel. This method does mark the value as seen.

Note there are two behavioral differences on when these two methods return
an error.

- [`has_changed`] errors if and only if the channel is closed.
- [`changed`] errors if the channel has been closed __AND__
  the current value is seen.

See the example below that shows how these methods have different fallibility.

### tokio::sync::watch (module) › [`borrow_and_update`] versus [`borrow`]

If the receiver intends to await notifications from [`changed`] in a loop,
[`Receiver::borrow_and_update()`] should be preferred over
[`Receiver::borrow()`].  This avoids a potential race where a new value is
sent between [`changed`] being ready and the value being read. (If
[`Receiver::borrow()`] is used, the loop may run twice with the same value.)

If the receiver is only interested in the current value, and does not intend
to wait for changes, then [`Receiver::borrow()`] can be used. It may be more
convenient to use [`borrow`](Receiver::borrow) since it's an `&self`
method---[`borrow_and_update`](Receiver::borrow_and_update) requires `&mut
self`.

### tokio::sync::watch (module) › Examples

The following example prints `hello! world! `.

```
use tokio::sync::watch;
use tokio::time::{Duration, sleep};

# async fn dox() -> Result<(), Box<dyn std::error::Error>> {
let (tx, mut rx) = watch::channel("hello");

tokio::spawn(async move {
    // Use the equivalent of a "do-while" loop so the initial value is
    // processed before awaiting the `changed()` future.
    loop {
        println!("{}! ", *rx.borrow_and_update());
        if rx.changed().await.is_err() {
            break;
        }
    }
});

sleep(Duration::from_millis(100)).await;
tx.send("world")?;
# Ok(())
# }
```

Difference on fallibility of [`changed`] versus [`has_changed`].
```
use tokio::sync::watch;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = watch::channel("hello");
tx.send("goodbye").unwrap();
drop(tx);

// `has_changed` does not mark the value as seen and errors
// since the channel is closed.
assert!(rx.has_changed().is_err());

// `changed` returns Ok since the value is not already marked as seen
// even if the channel is closed.
assert!(rx.changed().await.is_ok());

// The `changed` call above marks the value as seen.
// The next `changed` call now returns an error as the channel is closed
// AND the current value is seen.
assert!(rx.changed().await.is_err());
# }
```

### tokio::sync::watch (module) › Closing

[`Sender::is_closed`] and [`Sender::closed`] allow the producer to detect
when all [`Receiver`] handles have been dropped. This indicates that there
is no further interest in the values being produced and work can be stopped.

The value in the channel will not be dropped until all senders and all
receivers have been dropped.

### tokio::sync::watch (module) › Thread safety

Both [`Sender`] and [`Receiver`] are thread safe. They can be moved to other
threads and can be used in a concurrent environment. Clones of [`Receiver`]
handles may be moved to separate threads and also used concurrently.

[`Sender`]: crate::sync::watch::Sender
[`Receiver`]: crate::sync::watch::Receiver
[`changed`]: crate::sync::watch::Receiver::changed
[`has_changed`]: crate::sync::watch::Receiver::has_changed
[`borrow`]: crate::sync::watch::Receiver::borrow
[`borrow_and_update`]: crate::sync::watch::Receiver::borrow_and_update
[`Receiver::changed()`]: crate::sync::watch::Receiver::changed
[`Receiver::borrow()`]: crate::sync::watch::Receiver::borrow
[`Receiver::borrow_and_update()`]:
    crate::sync::watch::Receiver::borrow_and_update
[`channel`]: crate::sync::watch::channel
[`Sender::is_closed`]: crate::sync::watch::Sender::is_closed
[`Sender::closed`]: crate::sync::watch::Sender::closed
[`Sender::subscribe()`]: crate::sync::watch::Sender::subscribe

## tokio::sync::watch::error (module)

Watch error types.

## tokio::task (module)

Asynchronous green-threads.

### tokio::task (module) › What are Tasks?

A _task_ is a light weight, non-blocking unit of execution. A task is similar
to an OS thread, but rather than being managed by the OS scheduler, they are
managed by the [Tokio runtime][rt]. Another name for this general pattern is
[green threads]. If you are familiar with [Go's goroutines], [Kotlin's
coroutines], or [Erlang's processes], you can think of Tokio's tasks as
something similar.

Key points about tasks include:

* Tasks are **light weight**. Because tasks are scheduled by the Tokio
  runtime rather than the operating system, creating new tasks or switching
  between tasks does not require a context switch and has fairly low
  overhead. Creating, running, and destroying large numbers of tasks is
  quite cheap, especially compared to OS threads.

* Tasks are scheduled **cooperatively**. Most operating systems implement
  _preemptive multitasking_. This is a scheduling technique where the
  operating system allows each thread to run for a period of time, and then
  _preempts_ it, temporarily pausing that thread and switching to another.
  Tasks, on the other hand, implement _cooperative multitasking_. In
  cooperative multitasking, a task is allowed to run until it _yields_,
  indicating to the Tokio runtime's scheduler that it cannot currently
  continue executing. When a task yields, the Tokio runtime switches to
  executing the next task.

* Tasks are **non-blocking**. Typically, when an OS thread performs I/O or
  must synchronize with another thread, it _blocks_, allowing the OS to
  schedule another thread. When a task cannot continue executing, it must
  yield instead, allowing the Tokio runtime to schedule another task. Tasks
  should generally not perform system calls or other operations that could
  block a thread, as this would prevent other tasks running on the same
  thread from executing as well. Instead, this module provides APIs for
  running blocking operations in an asynchronous context.

[rt]: crate::runtime
[green threads]: https://en.wikipedia.org/wiki/Green_threads
[Go's goroutines]: https://tour.golang.org/concurrency/1
[Kotlin's coroutines]: https://kotlinlang.org/docs/reference/coroutines-overview.html
[Erlang's processes]: http://erlang.org/doc/getting_started/conc_prog.html#processes

### tokio::task (module) › Working with Tasks

This module provides the following APIs for working with tasks:

### tokio::task (module) › Spawning

Perhaps the most important function in this module is [`task::spawn`]. This
function can be thought of as an async equivalent to the standard library's
[`thread::spawn`][`std::thread::spawn`]. It takes an `async` block or other
[future], and creates a new task to run that work concurrently:

```
use tokio::task;

# async fn doc() {
task::spawn(async {
    // perform some work here...
});
# }
```

Like [`std::thread::spawn`], `task::spawn` returns a [`JoinHandle`] struct.
A `JoinHandle` is itself a future which may be used to await the output of
the spawned task. For example:

```
use tokio::task;

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> Result<(), Box<dyn std::error::Error>> {
let join = task::spawn(async {
    // ...
    "hello world!"
});

// ...

// Await the result of the spawned task.
let result = join.await?;
assert_eq!(result, "hello world!");
# Ok(())
# }
```

Again, like `std::thread`'s [`JoinHandle` type][thread_join], if the spawned
task panics, awaiting its `JoinHandle` will return a [`JoinError`]. For
example:

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::task;

# #[tokio::main] async fn main() {
let join = task::spawn(async {
    panic!("something bad happened!")
});

// The returned result indicates that the task failed.
assert!(join.await.is_err());
# }
# }
```

`spawn`, `JoinHandle`, and `JoinError` are present when the "rt"
feature flag is enabled.

[`task::spawn`]: crate::task::spawn()
[future]: std::future::Future
[`std::thread::spawn`]: std::thread::spawn
[`JoinHandle`]: crate::task::JoinHandle
[thread_join]: std::thread::JoinHandle
[`JoinError`]: crate::task::JoinError

### tokio::task (module) › Cancellation

Spawned tasks may be cancelled using the [`JoinHandle::abort`] or
[`AbortHandle::abort`] methods. When one of these methods are called, the
task is signalled to shut down next time it yields at an `.await` point. If
the task is already idle, then it will be shut down as soon as possible
without running again before being shut down. Additionally, shutting down a
Tokio runtime (e.g. by returning from `#[tokio::main]`) immediately cancels
all tasks on it.

When tasks are shut down, it will stop running at whichever `.await` it has
yielded at. All local variables are destroyed by running their destructor.
Once shutdown has completed, awaiting the [`JoinHandle`] will fail with a
[cancelled error](crate::task::JoinError::is_cancelled).

Note that aborting a task does not guarantee that it fails with a cancelled
error, since it may complete normally first. For example, if the task does
not yield to the runtime at any point between the call to `abort` and the
end of the task, then the [`JoinHandle`] will instead report that the task
exited normally.

Be aware that tasks spawned using [`spawn_blocking`] cannot be aborted
because they are not async. If you call `abort` on a `spawn_blocking`
task, then this *will not have any effect*, and the task will continue
running normally. The exception is if the task has not started running
yet; in that case, calling `abort` may prevent the task from starting.

Be aware that calls to [`JoinHandle::abort`] just schedule the task for
cancellation, and will return before the cancellation has completed. To wait
for cancellation to complete, wait for the task to finish by awaiting the
[`JoinHandle`]. Similarly, the [`JoinHandle::is_finished`] method does not
return `true` until the cancellation has finished.

Calling [`JoinHandle::abort`] multiple times has the same effect as calling
it once.

Tokio also provides an [`AbortHandle`], which is like the [`JoinHandle`],
except that it does not provide a mechanism to wait for the task to finish.
Each task can only have one [`JoinHandle`], but it can have more than one
[`AbortHandle`].

[`JoinHandle::abort`]: crate::task::JoinHandle::abort
[`AbortHandle::abort`]: crate::task::AbortHandle::abort
[`AbortHandle`]: crate::task::AbortHandle
[`JoinHandle::is_finished`]: crate::task::JoinHandle::is_finished

### tokio::task (module) › Blocking and Yielding

As we discussed above, code running in asynchronous tasks should not perform
operations that can block. A blocking operation performed in a task running
on a thread that is also running other tasks would block the entire thread,
preventing other tasks from running.

Instead, Tokio provides two APIs for running blocking operations in an
asynchronous context: [`task::spawn_blocking`] and [`task::block_in_place`].

Be aware that if you call a non-async method from async code, that non-async
method is still inside the asynchronous context, so you should also avoid
blocking operations there. This includes destructors of objects destroyed in
async code.

### tokio::task (module) › `spawn_blocking`

The `task::spawn_blocking` function is similar to the `task::spawn` function
discussed in the previous section, but rather than spawning a
_non-blocking_ future on the Tokio runtime, it instead spawns a
_blocking_ function on a dedicated thread pool for blocking tasks. For
example:

```
use tokio::task;

# async fn docs() {
task::spawn_blocking(|| {
    // do some compute-heavy work or call synchronous code
});
# }
```

Just like `task::spawn`, `task::spawn_blocking` returns a `JoinHandle`
which we can use to await the result of the blocking operation:

```rust
# use tokio::task;
# async fn docs() -> Result<(), Box<dyn std::error::Error>>{
let join = task::spawn_blocking(|| {
    // do some compute-heavy work or call synchronous code
    "blocking completed"
});

let result = join.await?;
assert_eq!(result, "blocking completed");
# Ok(())
# }
```

### tokio::task (module) › `block_in_place`

When using the [multi-threaded runtime][rt-multi-thread], the [`task::block_in_place`]
function is also available. Like `task::spawn_blocking`, this function
allows running a blocking operation from an asynchronous context. Unlike
`spawn_blocking`, however, `block_in_place` works by transitioning the
_current_ worker thread to a blocking thread, moving other tasks running on
that thread to another worker thread. This can improve performance by avoiding
context switches.

For example:

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::task;

# async fn docs() {
let result = task::block_in_place(|| {
    // do some compute-heavy work or call synchronous code
    "blocking completed"
});

assert_eq!(result, "blocking completed");
# }
# }
```

### tokio::task (module) › `yield_now`

In addition, this module provides a [`task::yield_now`] async function
that is analogous to the standard library's [`thread::yield_now`]. Calling
and `await`ing this function will cause the current task to yield to the
Tokio runtime's scheduler, allowing other tasks to be
scheduled. Eventually, the yielding task will be polled again, allowing it
to execute. For example:

```rust
use tokio::task;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
async {
    task::spawn(async {
        // ...
        println!("spawned task done!")
    });

    // Yield, allowing the newly-spawned task to execute first.
    task::yield_now().await;
    println!("main task done!");
}
# .await;
# }
```

[`task::spawn_blocking`]: crate::task::spawn_blocking
[`task::block_in_place`]: crate::task::block_in_place
[rt-multi-thread]: ../runtime/index.html#threaded-scheduler
[`task::yield_now`]: crate::task::yield_now()
[`thread::yield_now`]: std::thread::yield_now

## tokio::task::coop (module)

Utilities for improved cooperative scheduling.

### tokio::task::coop (module) › Cooperative scheduling

A single call to [`poll`] on a top-level task may potentially do a lot of
work before it returns `Poll::Pending`. If a task runs for a long period of
time without yielding back to the executor, it can starve other tasks
waiting on that executor to execute them, or drive underlying resources.
Since Rust does not have a runtime, it is difficult to forcibly preempt a
long-running task. Instead, this module provides an opt-in mechanism for
futures to collaborate with the executor to avoid starvation.

Consider a future like this one:

```
# use tokio_stream::{Stream, StreamExt};
async fn drop_all<I: Stream + Unpin>(mut input: I) {
    while let Some(_) = input.next().await {}
}
```

It may look harmless, but consider what happens under heavy load if the
input stream is _always_ ready. If we spawn `drop_all`, the task will never
yield, and will starve other tasks and resources on the same executor.

To account for this, Tokio has explicit yield points in a number of library
functions, which force tasks to return to the executor periodically.


### tokio::task::coop (module) › unconstrained

If necessary, [`task::unconstrained`] lets you opt a future out of Tokio's cooperative
scheduling. When a future is wrapped with `unconstrained`, it will never be forced to yield to
Tokio. For example:

```
# #[tokio::main(flavor = "current_thread")]
# async fn main() {
use tokio::{task, sync::mpsc};

let fut = async {
    let (tx, mut rx) = mpsc::unbounded_channel();

    for i in 0..1000 {
        let _ = tx.send(());
        // This will always be ready. If coop was in effect, this code would be forced to yield
        // periodically. However, if left unconstrained, then this code will never yield.
        rx.recv().await;
    }
};

task::coop::unconstrained(fut).await;
# }
```
[`poll`]: method@std::future::Future::poll
[`task::unconstrained`]: crate::task::unconstrained()

## tokio::task::futures (module)

Task-related futures.

## tokio::task::join_set (module)

A collection of tasks spawned on a Tokio runtime.

This module provides the [`JoinSet`] type, a collection which stores a set
of spawned tasks and allows asynchronously awaiting the output of those
tasks as they complete. See the documentation for the [`JoinSet`] type for
details.

## tokio::time (module)

Utilities for tracking time.

This module provides a number of types for executing code after a set period
of time.

* [`Sleep`] is a future that does no work and completes at a specific [`Instant`]
  in time.

* [`Interval`] is a stream yielding a value at a fixed period. It is
  initialized with a [`Duration`] and repeatedly yields each time the duration
  elapses.

* [`Timeout`]: Wraps a future or stream, setting an upper bound to the amount
  of time it is allowed to execute. If the future or stream does not
  complete in time, then it is canceled and an error is returned.

These types are sufficient for handling a large number of scenarios
involving time.

These types must be used from within the context of the [`Runtime`](crate::runtime::Runtime).

### tokio::time (module) › Examples

Wait 100ms and print "100 ms have elapsed"

```
use std::time::Duration;
use tokio::time::sleep;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
sleep(Duration::from_millis(100)).await;
println!("100 ms have elapsed");
# }
```

Require that an operation takes no more than 1s.

```
use tokio::time::{timeout, Duration};

async fn long_future() {
    // do work here
}

# async fn dox() {
let res = timeout(Duration::from_secs(1), long_future()).await;

if res.is_err() {
    println!("operation timed out");
}
# }
```

A simple example using [`interval`] to execute a task every two seconds.

The difference between [`interval`] and [`sleep`] is that an [`interval`]
measures the time since the last tick, which means that `.tick().await` may
wait for a shorter time than the duration specified for the interval
if some time has passed between calls to `.tick().await`.

If the tick in the example below was replaced with [`sleep`], the task
would only be executed once every three seconds, and not every two
seconds.

```
use tokio::time;

async fn task_that_takes_a_second() {
    println!("hello");
    time::sleep(time::Duration::from_secs(1)).await
}

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let mut interval = time::interval(time::Duration::from_secs(2));
for _i in 0..5 {
    interval.tick().await;
    task_that_takes_a_second().await;
}
# }
```

[`interval`]: crate::time::interval()
[`sleep`]: sleep()

## tokio::time::error (module)

Time error types.

## tokio (impl)

Collect an iterator of futures into a [`JoinSet`].

This is equivalent to calling [`JoinSet::spawn`] on each element of the iterator.

### tokio (impl) › Examples

The main example from [`JoinSet`]'s documentation can also be written using [`collect`]:

```
use tokio::task::JoinSet;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let mut set: JoinSet<_> = (0..10).map(|i| async move { i }).collect();

let mut seen = [false; 10];
while let Some(res) = set.join_next().await {
    let idx = res.unwrap();
    seen[idx] = true;
}

for i in 0..10 {
     assert!(seen[i]);
}
# }
```

[`collect`]: std::iter::Iterator::collect

## tokio (impl)

Extend a [`JoinSet`] with futures from an iterator.

This is equivalent to calling [`JoinSet::spawn`] on each element of the iterator.

### tokio (impl) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::task::JoinSet;

#[tokio::main]
async fn main() {
    let mut set: JoinSet<_> = (0..5).map(|i| async move { i }).collect();

    set.extend((5..10).map(|i| async move { i }));

    let mut seen = [false; 10];
    while let Some(res) = set.join_next().await {
        let idx = res.unwrap();
        seen[idx] = true;
    }

    for i in 0..10 {
        assert!(seen[i]);
    }
}
# }
```

## tokio (impl)

Seek to an offset, in bytes, in the underlying stream.

The position used for seeking with `SeekFrom::Current(_)` is the
position the underlying stream would be at if the `BufStream` had no
internal buffer.

Seeking always discards the internal buffer, even if the seek position
would otherwise fall within it. This guarantees that calling
`.into_inner()` immediately after a seek yields the underlying reader
at the same position.

See [`AsyncSeek`] for more details.

Note: In the edge case where you're seeking with `SeekFrom::Current(n)`
where `n` minus the internal buffer length overflows an `i64`, two
seeks will be performed instead of one. If the second seek returns
`Err`, the underlying reader will be left at the same position it would
have if you called `seek` with `SeekFrom::Current(0)`.

## tokio (impl)

Seek to the offset, in bytes, in the underlying writer.

Seeking always writes out the internal buffer before seeking.

## tokio (impl)

Seeks to an offset, in bytes, in the underlying reader.

The position used for seeking with `SeekFrom::Current(_)` is the
position the underlying reader would be at if the `BufReader` had no
internal buffer.

Seeking always discards the internal buffer, even if the seek position
would otherwise fall within it. This guarantees that calling
`.into_inner()` immediately after a seek yields the underlying reader
at the same position.

See [`AsyncSeek`] for more details.

Note: In the edge case where you're seeking with `SeekFrom::Current(n)`
where `n` minus the internal buffer length overflows an `i64`, two
seeks will be performed instead of one. If the second seek returns
`Err`, the underlying reader will be left at the same position it would
have if you called `seek` with `SeekFrom::Current(0)`.

## tokio::AIO (assoc_const)

Interest for POSIX AIO.

## tokio::ALL (assoc_const)

Returns a `Ready` representing readiness for all operations.

## tokio::EMPTY (assoc_const)

Returns the empty `Ready` set.

## tokio::ERROR (assoc_const)

Interest in error events.

Passes error interest to the underlying OS selector.
Behavior is platform-specific, read your platform's documentation.

## tokio::ERROR (assoc_const)

Returns a `Ready` representing error readiness.

## tokio::LIO (assoc_const)

Interest for POSIX AIO `lio_listio` events.

## tokio::MAX_PERMITS (assoc_const)

The maximum number of permits which a semaphore can hold. It is `usize::MAX >> 3`.

Exceeding this limit typically results in a panic.

## tokio::PRIORITY (assoc_const)

Returns a `Interest` set representing priority completion interests.

## tokio::PRIORITY (assoc_const)

Returns a `Ready` representing priority readiness.

## tokio::READABLE (assoc_const)

Interest in all readable events.

Readable interest includes read-closed events.

## tokio::READABLE (assoc_const)

Returns a `Ready` representing readable readiness.

## tokio::READ_CLOSED (assoc_const)

Returns a `Ready` representing read closed readiness.

## tokio::WRITABLE (assoc_const)

Interest in all writable events.

Writable interest includes write-closed events.

## tokio::WRITABLE (assoc_const)

Returns a `Ready` representing writable readiness.

## tokio::WRITE_CLOSED (assoc_const)

Returns a `Ready` representing write closed readiness.

## tokio::abort (function)

Abort the task associated with the handle.

Awaiting a cancelled task might complete as usual if the task was
already completed at the time it was cancelled, but most likely it
will fail with a [cancelled] `JoinError`.

Be aware that tasks spawned using [`spawn_blocking`] cannot be aborted
because they are not async. If you call `abort` on a `spawn_blocking`
task, then this *will not have any effect*, and the task will continue
running normally. The exception is if the task has not started running
yet; in that case, calling `abort` may prevent the task from starting.

See also [the module level docs] for more information on cancellation.

```rust
use tokio::time;

# #[tokio::main(flavor = "current_thread", start_paused = true)]
# async fn main() {
let mut handles = Vec::new();

handles.push(tokio::spawn(async {
   time::sleep(time::Duration::from_secs(10)).await;
   true
}));

handles.push(tokio::spawn(async {
   time::sleep(time::Duration::from_secs(10)).await;
   false
}));

for handle in &handles {
    handle.abort();
}

for handle in handles {
    assert!(handle.await.unwrap_err().is_cancelled());
}
# }
```

[cancelled]: method@super::error::JoinError::is_cancelled
[the module level docs]: crate::task#cancellation
[`spawn_blocking`]: crate::task::spawn_blocking

## tokio::abort (function)

Abort the task associated with the handle.

Awaiting a cancelled task might complete as usual if the task was
already completed at the time it was cancelled, but most likely it
will fail with a [cancelled] `JoinError`.

If the task was already cancelled, such as by [`JoinHandle::abort`],
this method will do nothing.

Be aware that tasks spawned using [`spawn_blocking`] cannot be aborted
because they are not async. If you call `abort` on a `spawn_blocking`
task, then this *will not have any effect*, and the task will continue
running normally. The exception is if the task has not started running
yet; in that case, calling `abort` may prevent the task from starting.

See also [the module level docs] for more information on cancellation.

[cancelled]: method@super::error::JoinError::is_cancelled
[`JoinHandle::abort`]: method@super::JoinHandle::abort
[the module level docs]: crate::task#cancellation
[`spawn_blocking`]: crate::task::spawn_blocking

## tokio::abort_all (function)

Aborts all tasks on this `JoinSet`.

This does not remove the tasks from the `JoinSet`. To wait for the tasks to complete
cancellation, you should call `join_next` in a loop until the `JoinSet` is empty.

## tokio::abort_handle (function)

Returns a new `AbortHandle` that can be used to remotely abort this task.

Awaiting a task cancelled by the `AbortHandle` might complete as usual if the task was
already completed at the time it was cancelled, but most likely it
will fail with a [cancelled] `JoinError`.

```rust
use tokio::{time, task};

# #[tokio::main(flavor = "current_thread", start_paused = true)]
# async fn main() {
let mut handles = Vec::new();

handles.push(tokio::spawn(async {
   time::sleep(time::Duration::from_secs(10)).await;
   true
}));

handles.push(tokio::spawn(async {
   time::sleep(time::Duration::from_secs(10)).await;
   false
}));

let abort_handles: Vec<task::AbortHandle> = handles.iter().map(|h| h.abort_handle()).collect();

for handle in abort_handles {
    handle.abort();
}

for handle in handles {
    assert!(handle.await.unwrap_err().is_cancelled());
}
# }
```
[cancelled]: method@super::error::JoinError::is_cancelled

## tokio::accept (function)

Accepts a new incoming connection from this listener.

This function will yield once a new TCP connection is established. When
established, the corresponding [`TcpStream`] and the remote peer's
address will be returned.

### tokio::accept (function) › Cancel safety

This method is cancel safe. If the method is used as a branch in
[`tokio::select!`](crate::select) and another branch
completes first, then it is guaranteed that no new connections were
accepted by this method.

[`TcpStream`]: struct@crate::net::TcpStream

### tokio::accept (function) › Examples

```no_run
use tokio::net::TcpListener;

use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:8080").await?;

    match listener.accept().await {
        Ok((_socket, addr)) => println!("new client: {:?}", addr),
        Err(e) => println!("couldn't get client: {:?}", e),
    }

    Ok(())
}
```

## tokio::accept (function)

Accepts a new incoming connection to this listener.

### tokio::accept (function) › Cancel safety

This method is cancel safe. If the method is used as a branch in
[`tokio::select!`](crate::select) and another branch
completes first, then it is guaranteed that no new connections were
accepted by this method.

## tokio::access_inbound (function)

The flow of data in the pipe goes from client to server only.

This corresponds to setting [`PIPE_ACCESS_INBOUND`].

[`PIPE_ACCESS_INBOUND`]: https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createnamedpipea#pipe_access_inbound

### tokio::access_inbound (function) › Errors

Server side prevents connecting by denying inbound access, client errors
with [`std::io::ErrorKind::PermissionDenied`] when attempting to create
the connection.

```
use std::io;
use tokio::net::windows::named_pipe::{ClientOptions, ServerOptions};

const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-access-inbound-err1";

# #[tokio::main] async fn main() -> io::Result<()> {
let _server = ServerOptions::new()
    .access_inbound(false)
    .create(PIPE_NAME)?;

let e = ClientOptions::new()
    .open(PIPE_NAME)
    .unwrap_err();

assert_eq!(e.kind(), io::ErrorKind::PermissionDenied);
# Ok(()) }
```

Disabling writing allows a client to connect, but errors with
[`std::io::ErrorKind::PermissionDenied`] if a write is attempted.

```
use std::io;
use tokio::io::AsyncWriteExt;
use tokio::net::windows::named_pipe::{ClientOptions, ServerOptions};

const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-access-inbound-err2";

# #[tokio::main] async fn main() -> io::Result<()> {
let server = ServerOptions::new()
    .access_inbound(false)
    .create(PIPE_NAME)?;

let mut client = ClientOptions::new()
    .write(false)
    .open(PIPE_NAME)?;

server.connect().await?;

let e = client.write(b"ping").await.unwrap_err();
assert_eq!(e.kind(), io::ErrorKind::PermissionDenied);
# Ok(()) }
```

### tokio::access_inbound (function) › Examples

A unidirectional named pipe that only supports server-to-client
communication.

```
use std::io;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::windows::named_pipe::{ClientOptions, ServerOptions};

const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-access-inbound";

# #[tokio::main] async fn main() -> io::Result<()> {
let mut server = ServerOptions::new()
    .access_inbound(false)
    .create(PIPE_NAME)?;

let mut client = ClientOptions::new()
    .write(false)
    .open(PIPE_NAME)?;

server.connect().await?;

let write = server.write_all(b"ping");

let mut buf = [0u8; 4];
let read = client.read_exact(&mut buf);

let ((), read) = tokio::try_join!(write, read)?;

assert_eq!(read, 4);
assert_eq!(&buf[..], b"ping");
# Ok(()) }
```

## tokio::access_mode (function)

Overrides the `dwDesiredAccess` argument to the call to [`CreateFile`]
with the specified value.

This will override the `read`, `write`, and `append` flags on the
`OpenOptions` structure. This method provides fine-grained control over
the permissions to read, write and append data, attributes (like hidden
and system), and extended attributes.

### tokio::access_mode (function) › Examples

```no_run
use tokio::fs::OpenOptions;

# #[tokio::main]
# async fn main() -> std::io::Result<()> {
// Open without read and write permission, for example if you only need
// to call `stat` on the file
let file = OpenOptions::new().access_mode(0).open("foo.txt").await?;
# Ok(())
# }
```

[`CreateFile`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea

## tokio::access_outbound (function)

The flow of data in the pipe goes from server to client only.

This corresponds to setting [`PIPE_ACCESS_OUTBOUND`].

[`PIPE_ACCESS_OUTBOUND`]: https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createnamedpipea#pipe_access_outbound

### tokio::access_outbound (function) › Errors

Server side prevents connecting by denying outbound access, client
errors with [`std::io::ErrorKind::PermissionDenied`] when attempting to
create the connection.

```
use std::io;
use tokio::net::windows::named_pipe::{ClientOptions, ServerOptions};

const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-access-outbound-err1";

# #[tokio::main] async fn main() -> io::Result<()> {
let server = ServerOptions::new()
    .access_outbound(false)
    .create(PIPE_NAME)?;

let e = ClientOptions::new()
    .open(PIPE_NAME)
    .unwrap_err();

assert_eq!(e.kind(), io::ErrorKind::PermissionDenied);
# Ok(()) }
```

Disabling reading allows a client to connect, but attempting to read
will error with [`std::io::ErrorKind::PermissionDenied`].

```
use std::io;
use tokio::io::AsyncReadExt;
use tokio::net::windows::named_pipe::{ClientOptions, ServerOptions};

const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-access-outbound-err2";

# #[tokio::main] async fn main() -> io::Result<()> {
let server = ServerOptions::new()
    .access_outbound(false)
    .create(PIPE_NAME)?;

let mut client = ClientOptions::new()
    .read(false)
    .open(PIPE_NAME)?;

server.connect().await?;

let mut buf = [0u8; 4];
let e = client.read(&mut buf).await.unwrap_err();
assert_eq!(e.kind(), io::ErrorKind::PermissionDenied);
# Ok(()) }
```

### tokio::access_outbound (function) › Examples

A unidirectional named pipe that only supports client-to-server
communication.

```
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::windows::named_pipe::{ClientOptions, ServerOptions};

const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-access-outbound";

# #[tokio::main] async fn main() -> std::io::Result<()> {
let mut server = ServerOptions::new()
    .access_outbound(false)
    .create(PIPE_NAME)?;

let mut client = ClientOptions::new()
    .read(false)
    .open(PIPE_NAME)?;

server.connect().await?;

let write = client.write_all(b"ping");

let mut buf = [0u8; 4];
let read = server.read_exact(&mut buf);

let ((), read) = tokio::try_join!(write, read)?;

println!("done reading and writing");

assert_eq!(read, 4);
assert_eq!(&buf[..], b"ping");
# Ok(()) }
```

## tokio::access_system_security (function)

Requests permission to modify the pipe's system access control list.

This corresponds to setting [`ACCESS_SYSTEM_SECURITY`] in dwOpenMode.

[`ACCESS_SYSTEM_SECURITY`]: https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createnamedpipea

## tokio::acquire (function)

Acquires a permit from the semaphore.

If the semaphore has been closed, this returns an [`AcquireError`].
Otherwise, this returns a [`SemaphorePermit`] representing the
acquired permit.

### tokio::acquire (function) › Cancel safety

This method uses a queue to fairly distribute permits in the order they
were requested. Cancelling a call to `acquire` makes you lose your place
in the queue.

### tokio::acquire (function) › Examples

```
use tokio::sync::Semaphore;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let semaphore = Semaphore::new(2);

let permit_1 = semaphore.acquire().await.unwrap();
assert_eq!(semaphore.available_permits(), 1);

let permit_2 = semaphore.acquire().await.unwrap();
assert_eq!(semaphore.available_permits(), 0);

drop(permit_1);
assert_eq!(semaphore.available_permits(), 1);
# }
```

[`AcquireError`]: crate::sync::AcquireError
[`SemaphorePermit`]: crate::sync::SemaphorePermit

## tokio::acquire_many (function)

Acquires `n` permits from the semaphore.

If the semaphore has been closed, this returns an [`AcquireError`].
Otherwise, this returns a [`SemaphorePermit`] representing the
acquired permits.

### tokio::acquire_many (function) › Cancel safety

This method uses a queue to fairly distribute permits in the order they
were requested. Cancelling a call to `acquire_many` makes you lose your
place in the queue.

### tokio::acquire_many (function) › Examples

```
use tokio::sync::Semaphore;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let semaphore = Semaphore::new(5);

let permit = semaphore.acquire_many(3).await.unwrap();
assert_eq!(semaphore.available_permits(), 2);
# }
```

[`AcquireError`]: crate::sync::AcquireError
[`SemaphorePermit`]: crate::sync::SemaphorePermit

## tokio::acquire_many_owned (function)

Acquires `n` permits from the semaphore.

The semaphore must be wrapped in an [`Arc`] to call this method.
If the semaphore has been closed, this returns an [`AcquireError`].
Otherwise, this returns a [`OwnedSemaphorePermit`] representing the
acquired permit.

### tokio::acquire_many_owned (function) › Cancel safety

This method uses a queue to fairly distribute permits in the order they
were requested. Cancelling a call to `acquire_many_owned` makes you lose
your place in the queue.

### tokio::acquire_many_owned (function) › Examples

```
use std::sync::Arc;
use tokio::sync::Semaphore;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let semaphore = Arc::new(Semaphore::new(10));
let mut join_handles = Vec::new();

for _ in 0..5 {
    let permit = semaphore.clone().acquire_many_owned(2).await.unwrap();
    join_handles.push(tokio::spawn(async move {
        // perform task...
        // explicitly own `permit` in the task
        drop(permit);
    }));
}

for handle in join_handles {
    handle.await.unwrap();
}
# }
```

[`Arc`]: std::sync::Arc
[`AcquireError`]: crate::sync::AcquireError
[`OwnedSemaphorePermit`]: crate::sync::OwnedSemaphorePermit

## tokio::acquire_owned (function)

Acquires a permit from the semaphore.

The semaphore must be wrapped in an [`Arc`] to call this method.
If the semaphore has been closed, this returns an [`AcquireError`].
Otherwise, this returns a [`OwnedSemaphorePermit`] representing the
acquired permit.

### tokio::acquire_owned (function) › Cancel safety

This method uses a queue to fairly distribute permits in the order they
were requested. Cancelling a call to `acquire_owned` makes you lose your
place in the queue.

### tokio::acquire_owned (function) › Examples

```
use std::sync::Arc;
use tokio::sync::Semaphore;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let semaphore = Arc::new(Semaphore::new(3));
let mut join_handles = Vec::new();

for _ in 0..5 {
    let permit = semaphore.clone().acquire_owned().await.unwrap();
    join_handles.push(tokio::spawn(async move {
        // perform task...
        // explicitly own `permit` in the task
        drop(permit);
    }));
}

for handle in join_handles {
    handle.await.unwrap();
}
# }
```

[`Arc`]: std::sync::Arc
[`AcquireError`]: crate::sync::AcquireError
[`OwnedSemaphorePermit`]: crate::sync::OwnedSemaphorePermit

## tokio::active_tasks_count (function)

Renamed to [`RuntimeMetrics::num_alive_tasks`]

## tokio::add (function)

Add together two `Interest` values.

This function works from a `const` context.

### tokio::add (function) › Examples

```
use tokio::io::Interest;

const BOTH: Interest = Interest::READABLE.add(Interest::WRITABLE);

assert!(BOTH.is_readable());
assert!(BOTH.is_writable());
```

## tokio::add_permits (function)

Adds `n` new permits to the semaphore.

The maximum number of permits is [`Semaphore::MAX_PERMITS`], and this function will panic if the limit is exceeded.

## tokio::addr (function)

Returns the starting address of this symbol.

## tokio::advance (function)

Advances the size of the filled region of the buffer.

The number of initialized bytes is not changed.

### tokio::advance (function) › Panics

Panics if the filled region of the buffer would become larger than the initialized region.

## tokio::alarm (function)

Represents the `SIGALRM` signal.

On Unix systems this signal is sent when a real-time timer has expired.
By default, the process is terminated by this signal.

## tokio::append (function)

Sets the option for the append mode.

This option, when true, means that writes will append to a file instead
of overwriting previous contents.  Note that setting
`.write(true).append(true)` has the same effect as setting only
`.append(true)`.

For most filesystems, the operating system guarantees that all writes are
atomic: no writes get mangled because another process writes at the same
time.

One maybe obvious note when using append-mode: make sure that all data
that belongs together is written to the file in one operation. This
can be done by concatenating strings before passing them to [`write()`],
or using a buffered writer (with a buffer of adequate size),
and calling [`flush()`] when the message is complete.

If a file is opened with both read and append access, beware that after
opening, and after every write, the position for reading may be set at the
end of the file. So, before writing, save the current position (using
[`seek`]`(`[`SeekFrom`]`::`[`Current`]`(0))`), and restore it before the next read.

This is an async version of [`std::fs::OpenOptions::append`][std]

[std]: std::fs::OpenOptions::append

### tokio::append (function) › Note

This function doesn't create the file if it doesn't exist. Use the [`create`]
method to do so.

[`write()`]: crate::io::AsyncWriteExt::write
[`flush()`]: crate::io::AsyncWriteExt::flush
[`seek`]: crate::io::AsyncSeekExt::seek
[`SeekFrom`]: std::io::SeekFrom
[`Current`]: std::io::SeekFrom::Current
[`create`]: OpenOptions::create

### tokio::append (function) › Examples

```no_run
use tokio::fs::OpenOptions;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let file = OpenOptions::new()
        .append(true)
        .open("foo.txt")
        .await?;

    Ok(())
}
```

## tokio::arg (function)

Adds an argument to pass to the program.

Only one argument can be passed per use. So instead of:

```no_run
let mut command = tokio::process::Command::new("sh");
command.arg("-C /path/to/repo");

# let _ = command.output(); // assert borrow checker
```

usage would be:

```no_run
let mut command = tokio::process::Command::new("sh");
command.arg("-C");
command.arg("/path/to/repo");

# let _ = command.output(); // assert borrow checker
```

To pass multiple arguments see [`args`].

[`args`]: method@Self::args

### tokio::arg (function) › Examples

Basic usage:

```no_run
# async fn test() { // allow using await
use tokio::process::Command;

let output = Command::new("ls")
        .arg("-l")
        .arg("-a")
        .output().await.unwrap();
# }

```

## tokio::arg0 (function)

Sets executable argument.

Set the first process argument, `argv[0]`, to something other than the
default executable path.

## tokio::args (function)

Adds multiple arguments to pass to the program.

To pass a single argument see [`arg`].

[`arg`]: method@Self::arg

### tokio::args (function) › Examples

Basic usage:

```no_run
# async fn test() { // allow using await
use tokio::process::Command;

let output = Command::new("ls")
        .args(&["-l", "-a"])
        .output().await.unwrap();
# }
```

## tokio::as_abstract_name (function)

Returns the contents of this address if it is in the abstract namespace.

Documentation reflected in [`SocketAddrExt`].
The abstract namespace is a Linux-specific feature.


[`SocketAddrExt`]: std::os::linux::net::SocketAddrExt

## tokio::as_handle (function)

See [`std::os::windows::io::AsHandle::as_handle`](https://doc.rust-lang.org/std/os/windows/io/trait.AsHandle.html#tymethod.as_handle)

## tokio::as_pathname (function)

Returns the contents of this address if it is a `pathname` address.

Documentation reflected in [`SocketAddr`].

[`SocketAddr`]: std::os::unix::net::SocketAddr

## tokio::as_raw_handle (function)

See [`std::os::windows::io::AsRawHandle::as_raw_handle`](https://doc.rust-lang.org/std/os/windows/io/trait.AsRawHandle.html#tymethod.as_raw_handle)

## tokio::as_raw_socket (function)

See [`std::os::windows::io::AsRawSocket::as_raw_socket`](https://doc.rust-lang.org/std/os/windows/io/trait.AsRawSocket.html#tymethod.as_raw_socket)

## tokio::as_raw_value (function)

Get the signal's numeric value.

```rust
# use tokio::signal::unix::SignalKind;
let kind = SignalKind::interrupt();
assert_eq!(kind.as_raw_value(), libc::SIGINT);
```

## tokio::as_socket (function)

See [`std::os::windows::io::AsSocket::as_socket`](https://doc.rust-lang.org/std/os/windows/io/trait.AsSocket.html#tymethod.as_socket)

## tokio::as_std (function)

Cheaply convert to a `&std::process::Command` for places where the type from the standard
library is expected.

## tokio::as_std_mut (function)

Cheaply convert to a `&mut std::process::Command` for places where the type from the
standard library is expected.

## tokio::assume_init (function)

Asserts that the first `n` unfilled bytes of the buffer are initialized.

`ReadBuf` assumes that bytes are never de-initialized, so this method does nothing when called with fewer
bytes than are already known to be initialized.

### tokio::assume_init (function) › Safety

The caller must ensure that `n` unfilled bytes of the buffer have already been initialized.

## tokio::async_io (function)

Reads or writes from the file descriptor using a user-provided IO operation.

The `async_io` method is a convenience utility that waits for the file
descriptor to become ready, and then executes the provided IO operation.
Since file descriptors may be marked ready spuriously, the closure will
be called repeatedly until it returns something other than a
[`WouldBlock`] error. This is done using the following loop:

```no_run
# use std::io::{self, Result};
# struct Dox<T> { inner: T }
# impl<T> Dox<T> {
#     async fn writable(&self) -> Result<&Self> {
#         Ok(self)
#     }
#     fn try_io<R>(&self, _: impl FnMut(&T) -> Result<R>) -> Result<Result<R>> {
#         panic!()
#     }
async fn async_io<R>(&self, mut f: impl FnMut(&T) -> io::Result<R>) -> io::Result<R> {
    loop {
        // or `readable` if called with the read interest.
        let guard = self.writable().await?;

        match guard.try_io(&mut f) {
            Ok(result) => return result,
            Err(_would_block) => continue,
        }
    }
}
# }
```

The closure should only return a [`WouldBlock`] error if it has performed
an IO operation on the file descriptor that failed due to the file descriptor not being
ready. Returning a [`WouldBlock`] error in any other situation will
incorrectly clear the readiness flag, which can cause the file descriptor to
behave incorrectly.

The closure should not perform the IO operation using any of the methods
defined on the Tokio [`AsyncFd`] type, as this will mess with the
readiness flag and can cause the file descriptor to behave incorrectly.

This method is not intended to be used with combined interests.
The closure should perform only one type of IO operation, so it should not
require more than one ready state. This method may panic or sleep forever
if it is called with a combined interest.

### tokio::async_io (function) › Examples

This example sends some bytes on the inner [`std::net::UdpSocket`]. The `async_io`
method waits for readiness, and retries if the send operation does block. This example
is equivalent to the one given for [`try_io`].

```no_run
use tokio::io::{Interest, unix::AsyncFd};

use std::io;
use std::net::UdpSocket;

#[tokio::main]
async fn main() -> io::Result<()> {
    let socket = UdpSocket::bind("0.0.0.0:8080")?;
    socket.set_nonblocking(true)?;
    let async_fd = AsyncFd::new(socket)?;

    let written = async_fd
        .async_io(Interest::WRITABLE, |inner| inner.send(&[1, 2]))
        .await?;

    println!("wrote {written} bytes");

    Ok(())
}
```

[`try_io`]: AsyncFdReadyGuard::try_io
[`WouldBlock`]: std::io::ErrorKind::WouldBlock

## tokio::async_io (function)

Reads or writes from the pipe using a user-provided IO operation.

The readiness of the pipe is awaited and when the pipe is ready,
the provided closure is called. The closure should attempt to perform
IO operation on the pipe by manually calling the appropriate syscall.
If the operation fails because the pipe is not actually ready,
then the closure should return a `WouldBlock` error. In such case the
readiness flag is cleared and the pipe readiness is awaited again.
This loop is repeated until the closure returns an `Ok` or an error
other than `WouldBlock`.

The closure should only return a `WouldBlock` error if it has performed
an IO operation on the pipe that failed due to the pipe not being
ready. Returning a `WouldBlock` error in any other situation will
incorrectly clear the readiness flag, which can cause the pipe to
behave incorrectly.

The closure should not perform the IO operation using any of the methods
defined on the Tokio `NamedPipeClient` type, as this will mess with the
readiness flag and can cause the pipe to behave incorrectly.

This method is not intended to be used with combined interests.
The closure should perform only one type of IO operation, so it should not
require more than one ready state. This method may panic or sleep forever
if it is called with a combined interest.

## tokio::async_io (function)

Reads or writes from the pipe using a user-provided IO operation.

The readiness of the pipe is awaited and when the pipe is ready,
the provided closure is called. The closure should attempt to perform
IO operation on the pipe by manually calling the appropriate syscall.
If the operation fails because the pipe is not actually ready,
then the closure should return a `WouldBlock` error. In such case the
readiness flag is cleared and the pipe readiness is awaited again.
This loop is repeated until the closure returns an `Ok` or an error
other than `WouldBlock`.

The closure should only return a `WouldBlock` error if it has performed
an IO operation on the pipe that failed due to the pipe not being
ready. Returning a `WouldBlock` error in any other situation will
incorrectly clear the readiness flag, which can cause the pipe to
behave incorrectly.

The closure should not perform the IO operation using any of the methods
defined on the Tokio `NamedPipeServer` type, as this will mess with the
readiness flag and can cause the pipe to behave incorrectly.

This method is not intended to be used with combined interests.
The closure should perform only one type of IO operation, so it should not
require more than one ready state. This method may panic or sleep forever
if it is called with a combined interest.

## tokio::async_io (function)

Reads or writes from the socket using a user-provided IO operation.

The readiness of the socket is awaited and when the socket is ready,
the provided closure is called. The closure should attempt to perform
IO operation on the socket by manually calling the appropriate syscall.
If the operation fails because the socket is not actually ready,
then the closure should return a `WouldBlock` error. In such case the
readiness flag is cleared and the socket readiness is awaited again.
This loop is repeated until the closure returns an `Ok` or an error
other than `WouldBlock`.

The closure should only return a `WouldBlock` error if it has performed
an IO operation on the socket that failed due to the socket not being
ready. Returning a `WouldBlock` error in any other situation will
incorrectly clear the readiness flag, which can cause the socket to
behave incorrectly.

The closure should not perform the IO operation using any of the methods
defined on the Tokio `TcpStream` type, as this will mess with the
readiness flag and can cause the socket to behave incorrectly.

This method is not intended to be used with combined interests.
The closure should perform only one type of IO operation, so it should not
require more than one ready state. This method may panic or sleep forever
if it is called with a combined interest.

## tokio::async_io (function)

Reads or writes from the socket using a user-provided IO operation.

The readiness of the socket is awaited and when the socket is ready,
the provided closure is called. The closure should attempt to perform
IO operation on the socket by manually calling the appropriate syscall.
If the operation fails because the socket is not actually ready,
then the closure should return a `WouldBlock` error. In such case the
readiness flag is cleared and the socket readiness is awaited again.
This loop is repeated until the closure returns an `Ok` or an error
other than `WouldBlock`.

The closure should only return a `WouldBlock` error if it has performed
an IO operation on the socket that failed due to the socket not being
ready. Returning a `WouldBlock` error in any other situation will
incorrectly clear the readiness flag, which can cause the socket to
behave incorrectly.

The closure should not perform the IO operation using any of the methods
defined on the Tokio `UdpSocket` type, as this will mess with the
readiness flag and can cause the socket to behave incorrectly.

This method is not intended to be used with combined interests.
The closure should perform only one type of IO operation, so it should not
require more than one ready state. This method may panic or sleep forever
if it is called with a combined interest.

## tokio::async_io (function)

Reads or writes from the socket using a user-provided IO operation.

The readiness of the socket is awaited and when the socket is ready,
the provided closure is called. The closure should attempt to perform
IO operation on the socket by manually calling the appropriate syscall.
If the operation fails because the socket is not actually ready,
then the closure should return a `WouldBlock` error. In such case the
readiness flag is cleared and the socket readiness is awaited again.
This loop is repeated until the closure returns an `Ok` or an error
other than `WouldBlock`.

The closure should only return a `WouldBlock` error if it has performed
an IO operation on the socket that failed due to the socket not being
ready. Returning a `WouldBlock` error in any other situation will
incorrectly clear the readiness flag, which can cause the socket to
behave incorrectly.

The closure should not perform the IO operation using any of the methods
defined on the Tokio `UnixStream` type, as this will mess with the
readiness flag and can cause the socket to behave incorrectly.

This method is not intended to be used with combined interests.
The closure should perform only one type of IO operation, so it should not
require more than one ready state. This method may panic or sleep forever
if it is called with a combined interest.

## tokio::async_io_mut (function)

Reads or writes from the file descriptor using a user-provided IO operation.

The behavior is the same as [`async_io`], except that the closure can mutate the inner
value of the [`AsyncFd`].

[`async_io`]: AsyncFd::async_io

## tokio::at_capacity (function)

Creates an error representing a timer at capacity.

## tokio::attributes (function)

Sets the `dwFileAttributes` argument to the call to [`CreateFile2`] to
the specified value (or combines it with `custom_flags` and
`security_qos_flags` to set the `dwFlagsAndAttributes` for
[`CreateFile`]).

If a _new_ file is created because it does not yet exist and
`.create(true)` or `.create_new(true)` are specified, the new file is
given the attributes declared with `.attributes()`.

If an _existing_ file is opened with `.create(true).truncate(true)`, its
existing attributes are preserved and combined with the ones declared
with `.attributes()`.

In all other cases the attributes get ignored.

### tokio::attributes (function) › Examples

```no_run
use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_HIDDEN;
use tokio::fs::OpenOptions;

# #[tokio::main]
# async fn main() -> std::io::Result<()> {
let file = OpenOptions::new()
    .write(true)
    .create(true)
    .attributes(FILE_ATTRIBUTE_HIDDEN)
    .open("foo.txt").await?;
# Ok(())
# }
```

[`CreateFile`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea
[`CreateFile2`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfile2

## tokio::available_permits (function)

Returns the current number of available permits.

## tokio::bind (function)

Binds the socket to the given address.

This calls the `bind(2)` operating-system function.

## tokio::bind (function)

Binds the socket to the given address.

This calls the `bind(2)` operating-system function. Behavior is
platform specific. Refer to the target platform's documentation for more
details.

### tokio::bind (function) › Examples

Bind a socket before listening.

```no_run
use tokio::net::TcpSocket;

use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let addr = "127.0.0.1:8080".parse().unwrap();

    let socket = TcpSocket::new_v4()?;
    socket.bind(addr)?;

    let listener = socket.listen(1024)?;
# drop(listener);

    Ok(())
}
```

## tokio::bind (function)

Creates a new `TcpListener`, which will be bound to the specified address.

The returned listener is ready for accepting connections.

Binding with a port number of 0 will request that the OS assigns a port
to this listener. The port allocated can be queried via the `local_addr`
method.

The address type can be any implementer of the [`ToSocketAddrs`] trait.
If `addr` yields multiple addresses, bind will be attempted with each of
the addresses until one succeeds and returns the listener. If none of
the addresses succeed in creating a listener, the error returned from
the last attempt (the last address) is returned.

This function sets the `SO_REUSEADDR` option on the socket on Unix.

To configure the socket before binding, you can use the [`TcpSocket`]
type.

[`ToSocketAddrs`]: trait@crate::net::ToSocketAddrs
[`TcpSocket`]: struct@crate::net::TcpSocket

### tokio::bind (function) › Examples

```no_run
use tokio::net::TcpListener;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:2345").await?;

    // use the listener

    # let _ = listener;
    Ok(())
}
```

## tokio::bind (function)

Creates a new `UnixListener` bound to the specified path.

### tokio::bind (function) › Panics

This function panics if it is not called from within a runtime with
IO enabled.

The runtime is usually set implicitly when this function is called
from a future driven by a tokio runtime, otherwise runtime can be set
explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.

## tokio::bind (function)

This function will create a new UDP socket and attempt to bind it to
the `addr` provided.

Binding with a port number of 0 will request that the OS assigns a port
to this listener. The port allocated can be queried via the `local_addr`
method.

### tokio::bind (function) › Example

```no_run
use tokio::net::UdpSocket;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
#   if cfg!(miri) { return Ok(()); } // No UDP sockets in miri.
    let sock = UdpSocket::bind("0.0.0.0:8080").await?;
    // use `sock`
#   let _ = sock;
    Ok(())
}
```

## tokio::bind_addr (function)

Creates a new `UnixListener` bound to the specified address.

### tokio::bind_addr (function) › Panics

This function panics if it is not called from within a runtime with
IO enabled.

The runtime is usually set implicitly when this function is called
from a future driven by a tokio runtime, otherwise runtime can be set
explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.

## tokio::bind_device (function)

Sets the value for the `SO_BINDTODEVICE` option on this socket

If a socket is bound to an interface, only packets received from that
particular interface are processed by the socket. Note that this only
works for some socket types, particularly `AF_INET` sockets.

If `interface` is `None` or an empty string it removes the binding.

## tokio::bind_device (function)

Sets the value for the `SO_BINDTODEVICE` option on this socket

If a socket is bound to an interface, only packets received from that
particular interface are processed by the socket. Note that this only
works for some socket types, particularly `AF_INET` sockets.

If `interface` is `None` or an empty string it removes the binding.

## tokio::block_on (function)

Runs a future to completion on the Tokio runtime. This is the
runtime's entry point.

See the documentation for [the equivalent method on Runtime][Runtime]
for more information.

[Runtime]: crate::runtime::Runtime::block_on

### tokio::block_on (function) › Examples

```no_run
use tokio::runtime::LocalRuntime;

// Create the runtime
let rt  = LocalRuntime::new().unwrap();

// Execute the future, blocking the current thread until completion
rt.block_on(async {
    println!("hello");
});
```

## tokio::block_on (function)

Runs a future to completion on the Tokio runtime. This is the
runtime's entry point.

This runs the given future on the current thread, blocking until it is
complete, and yielding its resolved result. Any tasks or timers
which the future spawns internally will be executed on the runtime.

### tokio::block_on (function) › Non-worker future

Note that the future required by this function does not run as a
worker. The expectation is that other tasks are spawned by the future here.
Awaiting on other futures from the future provided here will not
perform as fast as those spawned as workers.

### tokio::block_on (function) › Multi thread scheduler

When the multi thread scheduler is used this will allow futures
to run within the io driver and timer context of the overall runtime.

Any spawned tasks will continue running after `block_on` returns.

### tokio::block_on (function) › Current thread scheduler

When the current thread scheduler is enabled `block_on`
can be called concurrently from multiple threads. The first call
will take ownership of the io and timer drivers. This means
other threads which do not own the drivers will hook into that one.
When the first `block_on` completes, other threads will be able to
"steal" the driver to allow continued execution of their futures.

Any spawned tasks will be suspended after `block_on` returns. Calling
`block_on` again will resume previously spawned tasks.

### tokio::block_on (function) › Panics

This function panics if the provided future panics, or if called within an
asynchronous execution context.

### tokio::block_on (function) › Examples

```no_run
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime::Runtime;

// Create the runtime
let rt  = Runtime::new().unwrap();

// Execute the future, blocking the current thread until completion
rt.block_on(async {
    println!("hello");
});
# }
```

## tokio::block_on (function)

Runs a future to completion on the provided runtime, driving any local
futures spawned on this task set on the current thread.

This runs the given future on the runtime, blocking until it is
complete, and yielding its resolved result. Any tasks or timers which
the future spawns internally will be executed on the runtime. The future
may also call [`spawn_local`] to `spawn_local` additional local futures on the
current thread.

This method should not be called from an asynchronous context.

### tokio::block_on (function) › Panics

This function panics if the executor is at capacity, if the provided
future panics, or if called within an asynchronous execution context.

### tokio::block_on (function) › Notes

Since this function internally calls [`Runtime::block_on`], and drives
futures in the local task set inside that call to `block_on`, the local
futures may not use [in-place blocking]. If a blocking call needs to be
issued from a local task, the [`spawn_blocking`] API may be used instead.

For example, this will panic:
```should_panic,ignore-wasm
use tokio::runtime::Runtime;
use tokio::task;

let rt  = Runtime::new().unwrap();
let local = task::LocalSet::new();
local.block_on(&rt, async {
    let join = task::spawn_local(async {
        let blocking_result = task::block_in_place(|| {
            // ...
        });
        // ...
    });
    join.await.unwrap();
})
```
This, however, will not panic:
```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime::Runtime;
use tokio::task;

let rt  = Runtime::new().unwrap();
let local = task::LocalSet::new();
local.block_on(&rt, async {
    let join = task::spawn_local(async {
        let blocking_result = task::spawn_blocking(|| {
            // ...
        }).await;
        // ...
    });
    join.await.unwrap();
})
# }
```

[`spawn_local`]: fn@spawn_local
[`Runtime::block_on`]: method@crate::runtime::Runtime::block_on
[in-place blocking]: fn@crate::task::block_in_place
[`spawn_blocking`]: fn@crate::task::spawn_blocking

## tokio::block_on (function)

Runs a future to completion on this `Handle`'s associated `Runtime`.

This runs the given future on the current thread, blocking until it is
complete, and yielding its resolved result. Any tasks or timers which
the future spawns internally will be executed on the runtime.

When this is used on a `current_thread` runtime, only the
[`Runtime::block_on`] method can drive the IO and timer drivers, but the
`Handle::block_on` method cannot drive them. This means that, when using
this method on a `current_thread` runtime, anything that relies on IO or
timers will not work unless there is another thread currently calling
[`Runtime::block_on`] on the same runtime.

### tokio::block_on (function) › If the runtime has been shut down

If the `Handle`'s associated `Runtime` has been shut down (through
[`Runtime::shutdown_background`], [`Runtime::shutdown_timeout`], or by
dropping it) and `Handle::block_on` is used it might return an error or
panic. Specifically IO resources will return an error and timers will
panic. Runtime independent futures will run as normal.

### tokio::block_on (function) › Panics

This function will panic if any of the following conditions are met:
- The provided future panics.
- It is called from within an asynchronous context, such as inside
  [`Runtime::block_on`], `Handle::block_on`, or from a function annotated
  with [`tokio::main`].
- A timer future is executed on a runtime that has been shut down.

### tokio::block_on (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime::Runtime;

// Create the runtime
let rt  = Runtime::new().unwrap();

// Get a handle from this runtime
let handle = rt.handle();

// Execute the future, blocking the current thread until completion
handle.block_on(async {
    println!("hello");
});
# }
```

Or using `Handle::current`:

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime::Handle;

#[tokio::main]
async fn main () {
    let handle = Handle::current();
    std::thread::spawn(move || {
        // Using Handle::block_on to run async code in the new thread.
        handle.block_on(async {
            println!("hello");
        });
    });
}
# }
```

`Handle::block_on` may be combined with [`task::block_in_place`] to
re-enter the async context of a multi-thread scheduler runtime:
```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::task;
use tokio::runtime::Handle;

# async fn docs() {
task::block_in_place(move || {
    Handle::current().block_on(async move {
        // do something async
    });
});
# }
# }
```

[`JoinError`]: struct@crate::task::JoinError
[`JoinHandle`]: struct@crate::task::JoinHandle
[`Runtime::block_on`]: fn@crate::runtime::Runtime::block_on
[`Runtime::shutdown_background`]: fn@crate::runtime::Runtime::shutdown_background
[`Runtime::shutdown_timeout`]: fn@crate::runtime::Runtime::shutdown_timeout
[`spawn_blocking`]: crate::task::spawn_blocking
[`tokio::fs`]: crate::fs
[`tokio::net`]: crate::net
[`tokio::time`]: crate::time
[`tokio::main`]: ../attr.main.html
[`task::block_in_place`]: crate::task::block_in_place

## tokio::blocking_lock (function)

Blockingly locks this `Mutex`. When the lock has been acquired, function returns a
[`MutexGuard`].

This method is intended for use cases where you
need to use this mutex in asynchronous code as well as in synchronous code.

### tokio::blocking_lock (function) › Panics

This function panics if called within an asynchronous execution context.

  - If you find yourself in an asynchronous execution context and needing
    to call some (synchronous) function which performs one of these
    `blocking_` operations, then consider wrapping that call inside
    [`spawn_blocking()`][crate::runtime::Handle::spawn_blocking]
    (or [`block_in_place()`][crate::task::block_in_place]).

### tokio::blocking_lock (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use std::sync::Arc;
use tokio::sync::Mutex;

#[tokio::main]
async fn main() {
    let mutex =  Arc::new(Mutex::new(1));
    let lock = mutex.lock().await;

    let mutex1 = Arc::clone(&mutex);
    let blocking_task = tokio::task::spawn_blocking(move || {
        // This shall block until the `lock` is released.
        let mut n = mutex1.blocking_lock();
        *n = 2;
    });

    assert_eq!(*lock, 1);
    // Release the lock.
    drop(lock);

    // Await the completion of the blocking task.
    blocking_task.await.unwrap();

    // Assert uncontended.
    let n = mutex.try_lock().unwrap();
    assert_eq!(*n, 2);
}
# }
```

## tokio::blocking_lock_owned (function)

Blockingly locks this `Mutex`. When the lock has been acquired, function returns an
[`OwnedMutexGuard`].

This method is identical to [`Mutex::blocking_lock`], except that the returned
guard references the `Mutex` with an [`Arc`] rather than by borrowing
it. Therefore, the `Mutex` must be wrapped in an `Arc` to call this
method, and the guard will live for the `'static` lifetime, as it keeps
the `Mutex` alive by holding an `Arc`.

### tokio::blocking_lock_owned (function) › Panics

This function panics if called within an asynchronous execution context.

  - If you find yourself in an asynchronous execution context and needing
    to call some (synchronous) function which performs one of these
    `blocking_` operations, then consider wrapping that call inside
    [`spawn_blocking()`][crate::runtime::Handle::spawn_blocking]
    (or [`block_in_place()`][crate::task::block_in_place]).

### tokio::blocking_lock_owned (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use std::sync::Arc;
use tokio::sync::Mutex;

#[tokio::main]
async fn main() {
    let mutex =  Arc::new(Mutex::new(1));
    let lock = mutex.lock().await;

    let mutex1 = Arc::clone(&mutex);
    let blocking_task = tokio::task::spawn_blocking(move || {
        // This shall block until the `lock` is released.
        let mut n = mutex1.blocking_lock_owned();
        *n = 2;
    });

    assert_eq!(*lock, 1);
    // Release the lock.
    drop(lock);

    // Await the completion of the blocking task.
    blocking_task.await.unwrap();

    // Assert uncontended.
    let n = mutex.try_lock().unwrap();
    assert_eq!(*n, 2);
}
# }
```

## tokio::blocking_queue_depth (function)

Returns the number of tasks currently scheduled in the blocking
thread pool, spawned using `spawn_blocking`.

This metric returns the **current** number of tasks pending in
blocking thread pool. As such, the returned value may increase
or decrease as new tasks are scheduled and processed.

### tokio::blocking_queue_depth (function) › Examples

```
use tokio::runtime::Handle;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let metrics = Handle::current().metrics();

let n = metrics.blocking_queue_depth();
println!("{} tasks currently pending in the blocking thread pool", n);
# }
```

## tokio::blocking_read (function)

Blockingly locks this `RwLock` with shared read access.

This method is intended for use cases where you
need to use this rwlock in asynchronous code as well as in synchronous code.

Returns an RAII guard which will drop the read access of this `RwLock` when dropped.

### tokio::blocking_read (function) › Panics

This function panics if called within an asynchronous execution context.

  - If you find yourself in an asynchronous execution context and needing
    to call some (synchronous) function which performs one of these
    `blocking_` operations, then consider wrapping that call inside
    [`spawn_blocking()`][crate::runtime::Handle::spawn_blocking]
    (or [`block_in_place()`][crate::task::block_in_place]).

### tokio::blocking_read (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use std::sync::Arc;
use tokio::sync::RwLock;

#[tokio::main]
async fn main() {
    let rwlock = Arc::new(RwLock::new(1));
    let mut write_lock = rwlock.write().await;

    let blocking_task = tokio::task::spawn_blocking({
        let rwlock = Arc::clone(&rwlock);
        move || {
            // This shall block until the `write_lock` is released.
            let read_lock = rwlock.blocking_read();
            assert_eq!(*read_lock, 0);
        }
    });

    *write_lock -= 1;
    drop(write_lock); // release the lock.

    // Await the completion of the blocking task.
    blocking_task.await.unwrap();

    // Assert uncontended.
    assert!(rwlock.try_write().is_ok());
}
# }
```

## tokio::blocking_recv (function)

Blocking receive to call outside of asynchronous contexts.

### tokio::blocking_recv (function) › Panics

This function panics if called within an asynchronous execution
context.

### tokio::blocking_recv (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use std::thread;
use tokio::sync::mpsc;

#[tokio::main]
async fn main() {
    let (tx, mut rx) = mpsc::unbounded_channel::<u8>();

    let sync_code = thread::spawn(move || {
        assert_eq!(Some(10), rx.blocking_recv());
    });

    let _ = tx.send(10);
    sync_code.join().unwrap();
}
# }
```

## tokio::blocking_recv (function)

Blocking receive to call outside of asynchronous contexts.

### tokio::blocking_recv (function) › Panics

This function panics if called within an asynchronous execution
context.

### tokio::blocking_recv (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use std::thread;
use tokio::sync::oneshot;

#[tokio::main]
async fn main() {
    let (tx, rx) = oneshot::channel::<u8>();

    let sync_code = thread::spawn(move || {
        assert_eq!(Ok(10), rx.blocking_recv());
    });

    let _ = tx.send(10);
    sync_code.join().unwrap();
}
# }
```

## tokio::blocking_recv (function)

Blocking receive to call outside of asynchronous contexts.

### tokio::blocking_recv (function) › Panics

This function panics if called within an asynchronous execution
context.

### tokio::blocking_recv (function) › Examples
```
# #[cfg(not(target_family = "wasm"))]
# {
use std::thread;
use tokio::sync::broadcast;

#[tokio::main]
async fn main() {
    let (tx, mut rx) = broadcast::channel(16);

    let sync_code = thread::spawn(move || {
        assert_eq!(rx.blocking_recv(), Ok(10));
    });

    let _ = tx.send(10);
    sync_code.join().unwrap();
}
# }
```

## tokio::blocking_recv (function)

Blocking receive to call outside of asynchronous contexts.

This method returns `None` if the channel has been closed and there are
no remaining messages in the channel's buffer. This indicates that no
further values can ever be received from this `Receiver`. The channel is
closed when all senders have been dropped, or when [`close`] is called.

If there are no messages in the channel's buffer, but the channel has
not yet been closed, this method will block until a message is sent or
the channel is closed.

This method is intended for use cases where you are sending from
asynchronous code to synchronous code, and will work even if the sender
is not using [`blocking_send`] to send the message.

Note that if [`close`] is called, but there are still outstanding
[`Permits`] from before it was closed, the channel is not considered
closed by `blocking_recv` until the permits are released.

[`close`]: Self::close
[`Permits`]: struct@crate::sync::mpsc::Permit
[`blocking_send`]: fn@crate::sync::mpsc::Sender::blocking_send

### tokio::blocking_recv (function) › Panics

This function panics if called within an asynchronous execution
context.

### tokio::blocking_recv (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use std::thread;
use tokio::runtime::Runtime;
use tokio::sync::mpsc;

fn main() {
    let (tx, mut rx) = mpsc::channel::<u8>(10);

    let sync_code = thread::spawn(move || {
        assert_eq!(Some(10), rx.blocking_recv());
    });

    Runtime::new()
        .unwrap()
        .block_on(async move {
            let _ = tx.send(10).await;
        });
    sync_code.join().unwrap()
}
# }
```

## tokio::blocking_recv_many (function)

Variant of [`Self::recv_many`] for blocking contexts.

The same conditions as in [`Self::blocking_recv`] apply.

## tokio::blocking_recv_many (function)

Variant of [`Self::recv_many`] for blocking contexts.

The same conditions as in [`Self::blocking_recv`] apply.

## tokio::blocking_send (function)

Blocking send to call outside of asynchronous contexts.

This method is intended for use cases where you are sending from
synchronous code to asynchronous code, and will work even if the
receiver is not using [`blocking_recv`] to receive the message.

[`blocking_recv`]: fn@crate::sync::mpsc::Receiver::blocking_recv

### tokio::blocking_send (function) › Panics

This function panics if called within an asynchronous execution
context.

### tokio::blocking_send (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use std::thread;
use tokio::runtime::Runtime;
use tokio::sync::mpsc;

fn main() {
    let (tx, mut rx) = mpsc::channel::<u8>(1);

    let sync_code = thread::spawn(move || {
        tx.blocking_send(10).unwrap();
    });

    Runtime::new().unwrap().block_on(async move {
        assert_eq!(Some(10), rx.recv().await);
    });
    sync_code.join().unwrap()
}
# }
```

## tokio::blocking_write (function)

Blockingly locks this `RwLock` with exclusive write access.

This method is intended for use cases where you
need to use this rwlock in asynchronous code as well as in synchronous code.

Returns an RAII guard which will drop the write access of this `RwLock` when dropped.

### tokio::blocking_write (function) › Panics

This function panics if called within an asynchronous execution context.

  - If you find yourself in an asynchronous execution context and needing
    to call some (synchronous) function which performs one of these
    `blocking_` operations, then consider wrapping that call inside
    [`spawn_blocking()`][crate::runtime::Handle::spawn_blocking]
    (or [`block_in_place()`][crate::task::block_in_place]).

### tokio::blocking_write (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use std::sync::Arc;
use tokio::{sync::RwLock};

#[tokio::main]
async fn main() {
    let rwlock =  Arc::new(RwLock::new(1));
    let read_lock = rwlock.read().await;

    let blocking_task = tokio::task::spawn_blocking({
        let rwlock = Arc::clone(&rwlock);
        move || {
            // This shall block until the `read_lock` is released.
            let mut write_lock = rwlock.blocking_write();
            *write_lock = 2;
        }
    });

    assert_eq!(*read_lock, 1);
    // Release the last outstanding read lock.
    drop(read_lock);

    // Await the completion of the blocking task.
    blocking_task.await.unwrap();

    // Assert uncontended.
    let read_lock = rwlock.try_read().unwrap();
    assert_eq!(*read_lock, 2);
}
# }
```

## tokio::borrow (function)

Returns a reference to the most recently sent value

Outstanding borrows hold a read lock on the inner value. This means that
long-lived borrows could cause the producer half to block. It is recommended
to keep the borrow as short-lived as possible. Additionally, if you are
running in an environment that allows `!Send` futures, you must ensure that
the returned `Ref` type is never held alive across an `.await` point,
otherwise, it can lead to a deadlock.

### tokio::borrow (function) › Examples

```
use tokio::sync::watch;

let (tx, _) = watch::channel("hello");
assert_eq!(*tx.borrow(), "hello");
```

## tokio::borrow (function)

Returns a reference to the most recently sent value.

This method does not mark the returned value as seen, so future calls to
[`changed`] may return immediately even if you have already seen the
value with a call to `borrow`.

Outstanding borrows hold a read lock on the inner value. This means that
long-lived borrows could cause the producer half to block. It is recommended
to keep the borrow as short-lived as possible. Additionally, if you are
running in an environment that allows `!Send` futures, you must ensure that
the returned `Ref` type is never held alive across an `.await` point,
otherwise, it can lead to a deadlock.

The priority policy of the lock is dependent on the underlying lock
implementation, and this type does not guarantee that any particular policy
will be used. In particular, a producer which is waiting to acquire the lock
in `send` might or might not block concurrent calls to `borrow`, e.g.:

<details><summary>Potential deadlock example</summary>

```text
// Task 1 (on thread A)    |  // Task 2 (on thread B)
let _ref1 = rx.borrow();   |
                           |  // will block
                           |  let _ = tx.send(());
// may deadlock            |
let _ref2 = rx.borrow();   |
```
</details>

For more information on when to use this method versus
[`borrow_and_update`], see [here](self#borrow_and_update-versus-borrow).

[`changed`]: Receiver::changed
[`borrow_and_update`]: Receiver::borrow_and_update

### tokio::borrow (function) › Examples

```
use tokio::sync::watch;

let (_, rx) = watch::channel("hello");
assert_eq!(*rx.borrow(), "hello");
```

## tokio::borrow_and_update (function)

Returns a reference to the most recently sent value and marks that value
as seen.

This method marks the current value as seen. Subsequent calls to [`changed`]
will not return immediately until the [`Sender`] has modified the shared
value again.

Outstanding borrows hold a read lock on the inner value. This means that
long-lived borrows could cause the producer half to block. It is recommended
to keep the borrow as short-lived as possible. Additionally, if you are
running in an environment that allows `!Send` futures, you must ensure that
the returned `Ref` type is never held alive across an `.await` point,
otherwise, it can lead to a deadlock.

The priority policy of the lock is dependent on the underlying lock
implementation, and this type does not guarantee that any particular policy
will be used. In particular, a producer which is waiting to acquire the lock
in `send` might or might not block concurrent calls to `borrow`, e.g.:

<details><summary>Potential deadlock example</summary>

```text
// Task 1 (on thread A)                |  // Task 2 (on thread B)
let _ref1 = rx1.borrow_and_update();   |
                                       |  // will block
                                       |  let _ = tx.send(());
// may deadlock                        |
let _ref2 = rx2.borrow_and_update();   |
```
</details>

For more information on when to use this method versus [`borrow`], see
[here](self#borrow_and_update-versus-borrow).

[`changed`]: Receiver::changed
[`borrow`]: Receiver::borrow

## tokio::broadcast (function)

Gets the value of the `SO_BROADCAST` option for this socket.

For more information about this option, see [`set_broadcast`].

[`set_broadcast`]: method@Self::set_broadcast

## tokio::budget_forced_yield_count (function)

Returns the number of times that tasks have been forced to yield back to the scheduler
after exhausting their task budgets.

This count starts at zero when the runtime is created and increases by one each time a task yields due to exhausting its budget.

The counter is monotonically increasing. It is never decremented or
reset to zero.

## tokio::buffer (function)

Returns a reference to the internally buffered data.

## tokio::buffer (function)

Returns a reference to the internally buffered data.

Unlike `fill_buf`, this will not attempt to fill the buffer if it is empty.

## tokio::build (function)

Builds the log histogram

## tokio::build (function)

Creates the configured `Runtime`.

The returned `Runtime` instance is ready to spawn tasks.

### tokio::build (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime::Builder;

let rt  = Builder::new_multi_thread().build().unwrap();

rt.block_on(async {
    println!("Hello from the Tokio runtime");
});
# }
```

## tokio::build_local (function)

Creates the configured [`LocalRuntime`].

The returned [`LocalRuntime`] instance is ready to spawn tasks.

### tokio::build_local (function) › Panics

This will panic if the runtime is configured with [`new_multi_thread()`].

[`new_multi_thread()`]: Builder::new_multi_thread

### tokio::build_local (function) › Examples

```
use tokio::runtime::{Builder, LocalOptions};

let rt = Builder::new_current_thread()
    .build_local(LocalOptions::default())
    .unwrap();

rt.spawn_local(async {
    println!("Hello from the Tokio runtime");
});
```

## tokio::build_task (function)

Returns a [`Builder`] that can be used to configure a task prior to
spawning it on this `JoinSet`.

### tokio::build_task (function) › Examples

```
use tokio::task::JoinSet;

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let mut set = JoinSet::new();

    // Use the builder to configure a task's name before spawning it.
    set.build_task()
        .name("my_task")
        .spawn(async { /* ... */ })?;

    Ok(())
}
```

## tokio::builder (function)

Creates a builder for [`LogHistogram`]

## tokio::capacity (function)

Returns the current capacity of the channel.

The capacity goes down when sending a value by calling [`send`] or by reserving capacity
with [`reserve`]. The capacity goes up when values are received by the [`Receiver`].
This is distinct from [`max_capacity`], which always returns buffer capacity initially
specified when calling [`channel`]

### tokio::capacity (function) › Examples

```
use tokio::sync::mpsc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = mpsc::channel::<()>(5);

assert_eq!(tx.capacity(), 5);

// Making a reservation drops the capacity by one.
let permit = tx.reserve().await.unwrap();
assert_eq!(tx.capacity(), 4);

// Sending and receiving a value increases the capacity by one.
permit.send(());
rx.recv().await.unwrap();
assert_eq!(tx.capacity(), 5);
# }
```

[`send`]: Sender::send
[`reserve`]: Sender::reserve
[`channel`]: channel
[`max_capacity`]: Sender::max_capacity

## tokio::capacity (function)

Returns the current capacity of the channel.

The capacity goes down when the sender sends a value by calling [`Sender::send`] or by reserving
capacity with [`Sender::reserve`]. The capacity goes up when values are received.
This is distinct from [`max_capacity`], which always returns buffer capacity initially
specified when calling [`channel`].

### tokio::capacity (function) › Examples

```
use tokio::sync::mpsc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = mpsc::channel::<()>(5);

assert_eq!(rx.capacity(), 5);

// Making a reservation drops the capacity by one.
let permit = tx.reserve().await.unwrap();
assert_eq!(rx.capacity(), 4);
assert_eq!(rx.len(), 0);

// Sending and receiving a value increases the capacity by one.
permit.send(());
assert_eq!(rx.len(), 1);
rx.recv().await.unwrap();
assert_eq!(rx.capacity(), 5);

// Directly sending a message drops the capacity by one.
tx.send(()).await.unwrap();
assert_eq!(rx.capacity(), 4);
assert_eq!(rx.len(), 1);

// Receiving the message increases the capacity by one.
rx.recv().await.unwrap();
assert_eq!(rx.capacity(), 5);
assert_eq!(rx.len(), 0);
# }
```
[`capacity`]: Receiver::capacity
[`max_capacity`]: Receiver::max_capacity

## tokio::capacity (function)

Returns the total capacity of the buffer.

## tokio::capture (function)

Runs the function `f` in tracing mode, and returns its result along with the resulting [`Trace`].

This is normally called with `f` being the poll function of a future, and will give you a backtrace
that tells you what that one future is doing.

Use [`Handle::dump`] instead if you want to know what *all the tasks* in your program are doing.
Also see [`Handle::dump`] for more documentation about dumps, but unlike [`Handle::dump`], this function
should not be much slower than calling `f` directly.

Due to the way tracing is implemented, Tokio leaf futures will usually, instead of doing their
actual work, return `Poll::Pending` without registering the task's waker with any driver.
This means forward progress will probably not happen unless you eventually call your future
outside of `capture`, or explicitly re-schedule the task (e.g. by calling
[`cx.waker().wake_by_ref()`][std::task::Waker::wake_by_ref]) after `capture` returns.

[`Handle::dump`]: crate::runtime::Handle::dump

Example usage:
```
use std::future::Future;
use std::task::Poll;
use tokio::runtime::dump::Trace;

# async fn test_fn() {
// some future
let mut test_future = std::pin::pin!(async move { tokio::task::yield_now().await; 0 });

// trace it once, see what it's doing
let (trace, res) = Trace::root(std::future::poll_fn(|cx| {
    let (res, trace) = Trace::capture(|| test_future.as_mut().poll(cx));
    Poll::Ready((trace, res))
})).await;

// await it to let it finish, outside of a `capture`
let output = match res {
   Poll::Ready(output) => output,
   Poll::Pending => test_future.await,
};

println!("{trace}");
# }
```

### tokio::capture (function) › Nested calls

Nested calls to `capture` might return partial traces, but will not do any other undesirable behavior (for
example, they will not panic).

## tokio::chain (function)

Creates a new `AsyncRead` instance that chains this stream with
`next`.

The returned `AsyncRead` instance will first read all bytes from this object
until EOF is encountered. Afterwards the output is equivalent to the
output of `next`.

### tokio::chain (function) › Examples

[`File`][crate::fs::File]s implement `AsyncRead`:

```no_run
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::fs::File;
use tokio::io::{self, AsyncReadExt};

#[tokio::main]
async fn main() -> io::Result<()> {
    let f1 = File::open("foo.txt").await?;
    let f2 = File::open("bar.txt").await?;

    let mut handle = f1.chain(f2);
    let mut buffer = String::new();

    // read the value into a String. We could use any AsyncRead
    // method here, this is just one example.
    handle.read_to_string(&mut buffer).await?;
    Ok(())
}
# }
```

## tokio::changed (function)

Waits for a change notification, then marks the current value as seen.

If the current value in the channel has not yet been marked seen when
this method is called, the method marks that value seen and returns
immediately. If the newest value has already been marked seen, then the
method sleeps until a new message is sent by a [`Sender`] connected to
this `Receiver`, or until all [`Sender`]s are dropped.

For more information, see
[*Change notifications*](self#change-notifications) in the module-level documentation.

### tokio::changed (function) › Errors

Returns a [`RecvError`](error::RecvError) if the channel has been closed __AND__
the current value is seen.

### tokio::changed (function) › Cancel safety

This method is cancel safe. If you use it as a branch in
[`tokio::select!`](crate::select) and another branch
completes first, then it is guaranteed that no values have been marked
seen by this call to `changed`.

[`Sender`]: struct@Sender

### tokio::changed (function) › Examples

```
use tokio::sync::watch;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = watch::channel("hello");

tokio::spawn(async move {
    tx.send("goodbye").unwrap();
});

assert!(rx.changed().await.is_ok());
assert_eq!(*rx.borrow_and_update(), "goodbye");

// The `tx` handle has been dropped
assert!(rx.changed().await.is_err());
# }
```

## tokio::checked_add (function)

Returns `Some(t)` where `t` is the time `self + duration` if `t` can be
represented as `Instant` (which means it's inside the bounds of the
underlying data structure), `None` otherwise.

## tokio::checked_duration_since (function)

Returns the amount of time elapsed from another instant to this one, or
None if that instant is later than this one.

### tokio::checked_duration_since (function) › Examples

```
use tokio::time::{Duration, Instant, sleep};

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let now = Instant::now();
sleep(Duration::new(1, 0)).await;
let new_now = Instant::now();
println!("{:?}", new_now.checked_duration_since(now));
println!("{:?}", now.checked_duration_since(new_now)); // None
# }
```

## tokio::checked_sub (function)

Returns `Some(t)` where `t` is the time `self - duration` if `t` can be
represented as `Instant` (which means it's inside the bounds of the
underlying data structure), `None` otherwise.

## tokio::child (function)

Represents the `SIGCHLD` signal.

On Unix systems this signal is sent when the status of a child process
has changed. By default, this signal is ignored.

## tokio::clear (function)

Clears the buffer, resetting the filled region to empty.

The number of initialized bytes is not changed, and the contents of the buffer are not modified.

## tokio::clear_ready (function)

Indicates to Tokio that the source is no longer ready.  The internal
readiness flag will be cleared, and tokio will wait for the next
edge-triggered readiness notification from the OS.

It is critical that this method not be called unless your code
_actually observes_ that the source is _not_ ready.  The OS must
deliver a subsequent notification, or this source will block
forever.  It is equally critical that you `do` call this method if you
resubmit the same structure to the kernel and poll it again.

This method is not very useful with AIO readiness, since each `aiocb`
structure is typically only used once.  It's main use with
[`lio_listio`], which will sometimes send notification when only a
portion of its elements are complete.  In that case, the caller must
call `clear_ready` before resubmitting it.

[`lio_listio`]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/lio_listio.html

## tokio::clear_ready (function)

Indicates to tokio that the file descriptor is no longer ready. All
internal readiness flags will be cleared, and tokio will wait for the
next edge-triggered readiness notification from the OS.

This function is commonly used with guards returned by [`AsyncFd::readable_mut`] and
[`AsyncFd::writable_mut`].

It is critical that this function not be called unless your code
_actually observes_ that the file descriptor is _not_ ready. Do not call
it simply because, for example, a read succeeded; it should be called
when a read is observed to block.

This method only clears readiness events that happened before the creation of this guard.
In other words, if the IO resource becomes ready between the creation of the guard and
this call to `clear_ready`, then the readiness is not actually cleared.

## tokio::clear_ready (function)

Indicates to tokio that the file descriptor is no longer ready. All
internal readiness flags will be cleared, and tokio will wait for the
next edge-triggered readiness notification from the OS.

This function is commonly used with guards returned by [`AsyncFd::readable`] and
[`AsyncFd::writable`].

It is critical that this function not be called unless your code
_actually observes_ that the file descriptor is _not_ ready. Do not call
it simply because, for example, a read succeeded; it should be called
when a read is observed to block.

This method only clears readiness events that happened before the creation of this guard.
In other words, if the IO resource becomes ready between the creation of the guard and
this call to `clear_ready`, then the readiness is not actually cleared.

## tokio::clear_ready_matching (function)

Indicates to tokio that the file descriptor no longer has a specific readiness.
The internal readiness flag will be cleared, and tokio will wait for the
next edge-triggered readiness notification from the OS.

This function is useful in combination with the [`AsyncFd::ready_mut`] method when a
combined interest like `Interest::READABLE | Interest::WRITABLE` is used.

It is critical that this function not be called unless your code
_actually observes_ that the file descriptor is _not_ ready for the provided `Ready`.
Do not call it simply because, for example, a read succeeded; it should be called
when a read is observed to block. Only clear the specific readiness that is observed to
block. For example when a read blocks when using a combined interest,
only clear `Ready::READABLE`.

This method only clears readiness events that happened before the creation of this guard.
In other words, if the IO resource becomes ready between the creation of the guard and
this call to `clear_ready_matching`, then the readiness is not actually cleared.

### tokio::clear_ready_matching (function) › Examples

Concurrently read and write to a [`std::net::TcpStream`] on the same task without
splitting.

```no_run
use std::error::Error;
use std::io;
use std::io::{Read, Write};
use std::net::TcpStream;
use tokio::io::unix::AsyncFd;
use tokio::io::{Interest, Ready};

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let stream = TcpStream::connect("127.0.0.1:8080")?;
    stream.set_nonblocking(true)?;
    let mut stream = AsyncFd::new(stream)?;

    loop {
        let mut guard = stream
            .ready_mut(Interest::READABLE | Interest::WRITABLE)
            .await?;

        if guard.ready().is_readable() {
            let mut data = vec![0; 1024];
            // Try to read data, this may still fail with `WouldBlock`
            // if the readiness event is a false positive.
            match guard.get_inner_mut().read(&mut data) {
                Ok(n) => {
                    println!("read {} bytes", n);
                }
                Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                    // a read has blocked, but a write might still succeed.
                    // clear only the read readiness.
                    guard.clear_ready_matching(Ready::READABLE);
                    continue;
                }
                Err(e) => {
                    return Err(e.into());
                }
            }
        }

        if guard.ready().is_writable() {
            // Try to write data, this may still fail with `WouldBlock`
            // if the readiness event is a false positive.
            match guard.get_inner_mut().write(b"hello world") {
                Ok(n) => {
                    println!("write {} bytes", n);
                }
                Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                    // a write has blocked, but a read might still succeed.
                    // clear only the write readiness.
                    guard.clear_ready_matching(Ready::WRITABLE);
                    continue;
                }
                Err(e) => {
                    return Err(e.into());
                }
            }
        }
    }
}
```

## tokio::clear_ready_matching (function)

Indicates to tokio that the file descriptor no longer has a specific readiness.
The internal readiness flag will be cleared, and tokio will wait for the
next edge-triggered readiness notification from the OS.

This function is useful in combination with the [`AsyncFd::ready`] method when a
combined interest like `Interest::READABLE | Interest::WRITABLE` is used.

It is critical that this function not be called unless your code
_actually observes_ that the file descriptor is _not_ ready for the provided `Ready`.
Do not call it simply because, for example, a read succeeded; it should be called
when a read is observed to block. Only clear the specific readiness that is observed to
block. For example when a read blocks when using a combined interest,
only clear `Ready::READABLE`.

This method only clears readiness events that happened before the creation of this guard.
In other words, if the IO resource becomes ready between the creation of the guard and
this call to `clear_ready_matching`, then the readiness is not actually cleared.

### tokio::clear_ready_matching (function) › Examples

Concurrently read and write to a [`std::net::TcpStream`] on the same task without
splitting.

```no_run
use std::error::Error;
use std::io;
use std::io::{Read, Write};
use std::net::TcpStream;
use tokio::io::unix::AsyncFd;
use tokio::io::{Interest, Ready};

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let stream = TcpStream::connect("127.0.0.1:8080")?;
    stream.set_nonblocking(true)?;
    let stream = AsyncFd::new(stream)?;

    loop {
        let mut guard = stream
            .ready(Interest::READABLE | Interest::WRITABLE)
            .await?;

        if guard.ready().is_readable() {
            let mut data = vec![0; 1024];
            // Try to read data, this may still fail with `WouldBlock`
            // if the readiness event is a false positive.
            match stream.get_ref().read(&mut data) {
                Ok(n) => {
                    println!("read {} bytes", n);
                }
                Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                    // a read has blocked, but a write might still succeed.
                    // clear only the read readiness.
                    guard.clear_ready_matching(Ready::READABLE);
                    continue;
                }
                Err(e) => {
                    return Err(e.into());
                }
            }
        }

        if guard.ready().is_writable() {
            // Try to write data, this may still fail with `WouldBlock`
            // if the readiness event is a false positive.
            match stream.get_ref().write(b"hello world") {
                Ok(n) => {
                    println!("write {} bytes", n);
                }
                Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                    // a write has blocked, but a read might still succeed.
                    // clear only the write readiness.
                    guard.clear_ready_matching(Ready::WRITABLE);
                    continue;
                }
                Err(e) => {
                    return Err(e.into());
                }
            }
        }
    }
}
```

## tokio::clone (function)

Returns a cloned `AbortHandle` that can be used to remotely abort this task.

## tokio::close (function)

Closes the receiving half of a channel without dropping it.

This prevents any further messages from being sent on the channel while
still enabling the receiver to drain messages that are buffered. Any
outstanding [`Permit`] values will still be able to send messages.

To guarantee that no messages are dropped, after calling `close()`,
`recv()` must be called until `None` is returned. If there are
outstanding [`Permit`] or [`OwnedPermit`] values, the `recv` method will
not return `None` until those are released.

[`Permit`]: Permit
[`OwnedPermit`]: OwnedPermit

### tokio::close (function) › Examples

```
use tokio::sync::mpsc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = mpsc::channel(20);

tokio::spawn(async move {
    let mut i = 0;
    while let Ok(permit) = tx.reserve().await {
        permit.send(i);
        i += 1;
    }
});

rx.close();

while let Some(msg) = rx.recv().await {
    println!("got {}", msg);
}

// Channel closed and no messages are lost.
# }
```

## tokio::close (function)

Closes the receiving half of a channel, without dropping it.

This prevents any further messages from being sent on the channel while
still enabling the receiver to drain messages that are buffered.

To guarantee that no messages are dropped, after calling `close()`,
`recv()` must be called until `None` is returned.

## tokio::close (function)

Closes the semaphore.

This prevents the semaphore from issuing new permits and notifies all pending waiters.

### tokio::close (function) › Examples

```
use tokio::sync::Semaphore;
use std::sync::Arc;
use tokio::sync::TryAcquireError;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let semaphore = Arc::new(Semaphore::new(1));
let semaphore2 = semaphore.clone();

tokio::spawn(async move {
    let permit = semaphore.acquire_many(2).await;
    assert!(permit.is_err());
    println!("waiter received error");
});

println!("closing semaphore");
semaphore2.close();

// Cannot obtain more permits
assert_eq!(semaphore2.try_acquire().err(), Some(TryAcquireError::Closed))
# }
```

## tokio::close (function)

Prevents the associated [`Sender`] handle from sending a value.

Any `send` operation which happens after calling `close` is guaranteed
to fail. After calling `close`, [`try_recv`] should be called to
receive a value if one was sent **before** the call to `close`
completed.

This function is useful to perform a graceful shutdown and ensure that a
value will not be sent into the channel and never received.

`close` is no-op if a message is already received or the channel
is already closed.

[`Sender`]: Sender
[`try_recv`]: Receiver::try_recv

### tokio::close (function) › Examples

Prevent a value from being sent

```
use tokio::sync::oneshot;
use tokio::sync::oneshot::error::TryRecvError;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = oneshot::channel();

assert!(!tx.is_closed());

rx.close();

assert!(tx.is_closed());
assert!(tx.send("never received").is_err());

match rx.try_recv() {
    Err(TryRecvError::Closed) => {}
    _ => unreachable!(),
}
# }
```

Receive a value sent **before** calling `close`

```
use tokio::sync::oneshot;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = oneshot::channel();

assert!(tx.send("will receive").is_ok());

rx.close();

let msg = rx.try_recv().unwrap();
assert_eq!(msg, "will receive");
# }
```

## tokio::closed (function)

A future which completes when the number of [Receiver]s subscribed to this `Sender` reaches
zero.

### tokio::closed (function) › Examples

```
use futures::FutureExt;
use tokio::sync::broadcast;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx1) = broadcast::channel::<u32>(16);
let mut rx2 = tx.subscribe();

let _ = tx.send(10);

assert_eq!(rx1.recv().await.unwrap(), 10);
drop(rx1);
assert!(tx.closed().now_or_never().is_none());

assert_eq!(rx2.recv().await.unwrap(), 10);
drop(rx2);
assert!(tx.closed().now_or_never().is_some());
# }
```

## tokio::closed (function)

Completes when all receivers have dropped.

This allows the producer to get notified when interest in the produced
values is canceled and immediately stop doing work. Once a channel is
closed, the only way to reopen it is to call [`Sender::subscribe`] to
get a new receiver.

If the channel becomes closed for a brief amount of time (e.g., the last
receiver is dropped and then `subscribe` is called), then this call to
`closed` might return, but it is also possible that it does not "notice"
that the channel was closed for a brief amount of time.

### tokio::closed (function) › Cancel safety

This method is cancel safe.

### tokio::closed (function) › Examples

```
use tokio::sync::watch;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, rx) = watch::channel("hello");

tokio::spawn(async move {
    // use `rx`
    drop(rx);
});

// Waits for `rx` to drop
tx.closed().await;
println!("the `rx` handles dropped")
# }
```

## tokio::closed (function)

Completes when the receiver has dropped.

This allows the producers to get notified when interest in the produced
values is canceled and immediately stop doing work.

### tokio::closed (function) › Cancel safety

This method is cancel safe. Once the channel is closed, it stays closed
forever and all future calls to `closed` will return immediately.

### tokio::closed (function) › Examples

```
use tokio::sync::mpsc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx1, rx) = mpsc::channel::<()>(1);
let tx2 = tx1.clone();
let tx3 = tx1.clone();
let tx4 = tx1.clone();
let tx5 = tx1.clone();
tokio::spawn(async move {
    drop(rx);
});

futures::join!(
    tx1.closed(),
    tx2.closed(),
    tx3.closed(),
    tx4.closed(),
    tx5.closed()
);
println!("Receiver dropped");
# }
```

## tokio::closed (function)

Completes when the receiver has dropped.

This allows the producers to get notified when interest in the produced
values is canceled and immediately stop doing work.

### tokio::closed (function) › Cancel safety

This method is cancel safe. Once the channel is closed, it stays closed
forever and all future calls to `closed` will return immediately.

### tokio::closed (function) › Examples

```
use tokio::sync::mpsc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx1, rx) = mpsc::unbounded_channel::<()>();
let tx2 = tx1.clone();
let tx3 = tx1.clone();
let tx4 = tx1.clone();
let tx5 = tx1.clone();
tokio::spawn(async move {
    drop(rx);
});

futures::join!(
    tx1.closed(),
    tx2.closed(),
    tx3.closed(),
    tx4.closed(),
    tx5.closed()
);
println!("Receiver dropped");
# }
```

## tokio::closed (function)

Waits for the associated [`Receiver`] handle to close.

A [`Receiver`] is closed by either calling [`close`] explicitly or the
[`Receiver`] value is dropped.

This function is useful when paired with `select!` to abort a
computation when the receiver is no longer interested in the result.

### tokio::closed (function) › Return

Returns a `Future` which must be awaited on.

[`Receiver`]: Receiver
[`close`]: Receiver::close

### tokio::closed (function) › Examples

Basic usage

```
use tokio::sync::oneshot;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (mut tx, rx) = oneshot::channel::<()>();

tokio::spawn(async move {
    drop(rx);
});

tx.closed().await;
println!("the receiver dropped");
# }
```

Paired with select

```
use tokio::sync::oneshot;
use tokio::time::{self, Duration};

async fn compute() -> String {
    // Complex computation returning a `String`
# "hello".to_string()
}

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (mut tx, rx) = oneshot::channel();

tokio::spawn(async move {
    tokio::select! {
        _ = tx.closed() => {
            // The receiver dropped, no need to do any further work
        }
        value = compute() => {
            // The send can fail if the channel was closed at the exact same
            // time as when compute() finished, so just ignore the failure.
            let _ = tx.send(value);
        }
    }
});

// Wait for up to 10 seconds
let _ = time::timeout(Duration::from_secs(10), rx).await;
# }
```

## tokio::colno (function)

Returns the column number for where this symbol is currently executing.

If debuginfo is missing, this is likely to return `None`.

## tokio::connect (function)

Connects the UDP socket setting the default destination for send() and
limiting packets that are read via `recv` from the address specified in
`addr`.

### tokio::connect (function) › Example

```no_run
use tokio::net::UdpSocket;
# use std::{io, net::SocketAddr};

# #[tokio::main]
# async fn main() -> io::Result<()> {
let sock = UdpSocket::bind("0.0.0.0:8080".parse::<SocketAddr>().unwrap()).await?;

let remote_addr = "127.0.0.1:59600".parse::<SocketAddr>().unwrap();
sock.connect(remote_addr).await?;
let mut buf = [0u8; 32];
// recv from remote_addr
let len = sock.recv(&mut buf).await?;
// send to remote_addr
let _len = sock.send(&buf[..len]).await?;
# Ok(())
# }
```

## tokio::connect (function)

Connects to the socket named by `path`.

This function will create a new Unix socket and connect to the path
specified, associating the returned stream with the default event loop's
handle.

### tokio::connect (function) › Panics

This function panics if it is not called from within a runtime with
IO enabled.

The runtime is usually set implicitly when this function is called
from a future driven by a tokio runtime, otherwise runtime can be set
explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.

## tokio::connect (function)

Enables a named pipe server process to wait for a client process to
connect to an instance of a named pipe. A client process connects by
creating a named pipe with the same name.

This corresponds to the [`ConnectNamedPipe`] system call.

### tokio::connect (function) › Cancel safety

This method is cancel safe. If it is used as a branch in
[`select!`](crate::select) and another branch
completes first, then no connection events have been lost.

[`ConnectNamedPipe`]: https://docs.microsoft.com/en-us/windows/win32/api/namedpipeapi/nf-namedpipeapi-connectnamedpipe

### tokio::connect (function) › Example

```no_run
use tokio::net::windows::named_pipe::ServerOptions;

const PIPE_NAME: &str = r"\\.\pipe\mynamedpipe";

# #[tokio::main] async fn main() -> std::io::Result<()> {
let pipe = ServerOptions::new().create(PIPE_NAME)?;

// Wait for a client to connect.
pipe.connect().await?;

// Use the connected client...
# Ok(()) }
```

## tokio::connect (function)

Establishes a TCP connection with a peer at the specified socket address.

The `TcpSocket` is consumed. Once the connection is established, a
connected [`TcpStream`] is returned. If the connection fails, the
encountered error is returned.

[`TcpStream`]: TcpStream

This calls the `connect(2)` operating-system function. Behavior is
platform specific. Refer to the target platform's documentation for more
details.

### tokio::connect (function) › Examples

Connecting to a peer.

```no_run
use tokio::net::TcpSocket;

use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let addr = "127.0.0.1:8080".parse().unwrap();

    let socket = TcpSocket::new_v4()?;
    let stream = socket.connect(addr).await?;
# drop(stream);

    Ok(())
}
```

## tokio::connect (function)

Establishes a Unix connection with a peer at the specified socket address.

The `UnixSocket` is consumed. Once the connection is established, a
connected [`UnixStream`] is returned. If the connection fails, the
encountered error is returned.

Calling this function on a socket created by [`new_datagram`] will return an error.

This calls the `connect(2)` operating-system function.

[`new_datagram`]: `UnixSocket::new_datagram`

## tokio::connect (function)

Opens a TCP connection to a remote host.

`addr` is an address of the remote host. Anything which implements the
[`ToSocketAddrs`] trait can be supplied as the address.  If `addr`
yields multiple addresses, connect will be attempted with each of the
addresses until a connection is successful. If none of the addresses
result in a successful connection, the error returned from the last
connection attempt (the last address) is returned.

To configure the socket before connecting, you can use the [`TcpSocket`]
type.

[`ToSocketAddrs`]: trait@crate::net::ToSocketAddrs
[`TcpSocket`]: struct@crate::net::TcpSocket

### tokio::connect (function) › Examples

```no_run
use tokio::net::TcpStream;
use tokio::io::AsyncWriteExt;
use std::error::Error;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // Connect to a peer
    let mut stream = TcpStream::connect("127.0.0.1:8080").await?;

    // Write some data.
    stream.write_all(b"hello world!").await?;

    Ok(())
}
```

The [`write_all`] method is defined on the [`AsyncWriteExt`] trait.

[`write_all`]: fn@crate::io::AsyncWriteExt::write_all
[`AsyncWriteExt`]: trait@crate::io::AsyncWriteExt

## tokio::connect_addr (function)

Connects to the socket named by `socket_addr`.

This function will create a new Unix socket and connect to the address
specified, associating the returned stream with the default event
loop's handle.

### tokio::connect_addr (function) › Panics

This function panics if it is not called from within a runtime with
IO enabled.

The runtime is usually set implicitly when this function is called
from a future driven by a tokio runtime, otherwise runtime can be set
explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.

## tokio::const_new (function)

Create a new `Notify`, initialized without a permit.

When using the `tracing` [unstable feature], a `Notify` created with
`const_new` will not be instrumented. As such, it will not be visible
in [`tokio-console`]. Instead, [`Notify::new`] should be used to create
an instrumented object if that is needed.

### tokio::const_new (function) › Examples

```
use tokio::sync::Notify;

static NOTIFY: Notify = Notify::const_new();
```

[`tokio-console`]: https://github.com/tokio-rs/console
[unstable feature]: crate#unstable-features

## tokio::const_new (function)

Creates a new empty `OnceCell` instance.

Equivalent to `OnceCell::new`, except that it can be used in static
variables.

When using the `tracing` [unstable feature], a `OnceCell` created with
`const_new` will not be instrumented. As such, it will not be visible
in [`tokio-console`]. Instead, [`OnceCell::new`] should be used to
create an instrumented object if that is needed.

### tokio::const_new (function) › Example

```
use tokio::sync::OnceCell;

static ONCE: OnceCell<u32> = OnceCell::const_new();

async fn get_global_integer() -> &'static u32 {
    ONCE.get_or_init(|| async {
        1 + 1
    }).await
}

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let result = get_global_integer().await;
assert_eq!(*result, 2);
# }
```

[`tokio-console`]: https://github.com/tokio-rs/console
[unstable feature]: crate#unstable-features

## tokio::const_new (function)

Creates a new empty `SetOnce` instance.

Equivalent to `SetOnce::new`, except that it can be used in static
variables.

When using the `tracing` [unstable feature], a `SetOnce` created with
`const_new` will not be instrumented. As such, it will not be visible
in [`tokio-console`]. Instead, [`SetOnce::new`] should be used to
create an instrumented object if that is needed.

### tokio::const_new (function) › Example

```
use tokio::sync::{SetOnce, SetOnceError};

static ONCE: SetOnce<u32> = SetOnce::const_new();

fn get_global_integer() -> Result<Option<&'static u32>, SetOnceError<u32>> {
    ONCE.set(2)?;
    Ok(ONCE.get())
}

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> Result<(), SetOnceError<u32>> {
let result = get_global_integer()?;

assert_eq!(result, Some(&2));
Ok(())
# }
```

[`tokio-console`]: https://github.com/tokio-rs/console
[unstable feature]: crate#unstable-features

## tokio::const_new (function)

Creates a new instance of an `RwLock<T>` which is unlocked.

When using the `tracing` [unstable feature], a `RwLock` created with
`const_new` will not be instrumented. As such, it will not be visible
in [`tokio-console`]. Instead, [`RwLock::new`] should be used to create
an instrumented object if that is needed.

### tokio::const_new (function) › Examples

```
use tokio::sync::RwLock;

static LOCK: RwLock<i32> = RwLock::const_new(5);
```

[`tokio-console`]: https://github.com/tokio-rs/console
[unstable feature]: crate#unstable-features

## tokio::const_new (function)

Creates a new lock in an unlocked state ready for use.

When using the `tracing` [unstable feature], a `Mutex` created with
`const_new` will not be instrumented. As such, it will not be visible
in [`tokio-console`]. Instead, [`Mutex::new`] should be used to create
an instrumented object if that is needed.

### tokio::const_new (function) › Examples

```
use tokio::sync::Mutex;

static LOCK: Mutex<i32> = Mutex::const_new(5);
```

[`tokio-console`]: https://github.com/tokio-rs/console
[unstable feature]: crate#unstable-features

## tokio::const_new (function)

Creates a new semaphore with the initial number of permits.

When using the `tracing` [unstable feature], a `Semaphore` created with
`const_new` will not be instrumented. As such, it will not be visible
in [`tokio-console`]. Instead, [`Semaphore::new`] should be used to
create an instrumented object if that is needed.

### tokio::const_new (function) › Examples

```
use tokio::sync::Semaphore;

static SEM: Semaphore = Semaphore::const_new(10);
```

[`tokio-console`]: https://github.com/tokio-rs/console
[unstable feature]: crate#unstable-features

## tokio::const_new_with (function)

Creates a new `OnceCell` that contains the provided value.

### tokio::const_new_with (function) › Example

When using the `tracing` [unstable feature], a `OnceCell` created with
`const_new_with` will not be instrumented. As such, it will not be
visible in [`tokio-console`]. Instead, [`OnceCell::new_with`] should be
used to create an instrumented object if that is needed.

```
use tokio::sync::OnceCell;

static ONCE: OnceCell<u32> = OnceCell::const_new_with(1);

async fn get_global_integer() -> &'static u32 {
    ONCE.get_or_init(|| async {
        1 + 1
    }).await
}

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let result = get_global_integer().await;
assert_eq!(*result, 1);
# }
```

[`tokio-console`]: https://github.com/tokio-rs/console
[unstable feature]: crate#unstable-features

## tokio::const_new_with (function)

Creates a new `SetOnce` that contains the provided value.

### tokio::const_new_with (function) › Example

When using the `tracing` [unstable feature], a `SetOnce` created with
`const_new_with` will not be instrumented. As such, it will not be
visible in [`tokio-console`]. Instead, [`SetOnce::new_with`] should be
used to create an instrumented object if that is needed.

```
use tokio::sync::SetOnce;

static ONCE: SetOnce<u32> = SetOnce::const_new_with(1);

fn get_global_integer() -> Option<&'static u32> {
    ONCE.get()
}

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let result = get_global_integer();

assert_eq!(result, Some(&1));
# }
```

[`tokio-console`]: https://github.com/tokio-rs/console
[unstable feature]: crate#unstable-features

## tokio::const_with_max_readers (function)

Creates a new instance of an `RwLock<T>` which is unlocked
and allows a maximum of `max_reads` concurrent readers.

### tokio::const_with_max_readers (function) › Examples

```
use tokio::sync::RwLock;

static LOCK: RwLock<i32> = RwLock::const_with_max_readers(5, 1024);
```

### tokio::const_with_max_readers (function) › Panics

Panics if `max_reads` is `0` or is bigger than `u32::MAX >> 3`.

## tokio::consume (function)

Tells this buffer that `amt` bytes have been consumed from the
buffer, so they should no longer be returned in calls to [`read`].

This function is a lower-level call. It needs to be paired with the
[`fill_buf`] method to function properly. This function does not
perform any I/O, it simply informs this object that some amount of
its buffer, returned from [`fill_buf`], has been consumed and should
no longer be returned. As such, this function may do odd things if
[`fill_buf`] isn't called before calling it.

The `amt` must be less than the number of bytes in the buffer
returned by [`fill_buf`].

[`read`]: crate::io::AsyncReadExt::read
[`fill_buf`]: crate::io::AsyncBufReadExt::fill_buf

## tokio::consume (function)

Tells this buffer that `amt` bytes have been consumed from the buffer,
so they should no longer be returned in calls to [`poll_read`].

This function is a lower-level call. It needs to be paired with the
[`poll_fill_buf`] method to function properly. This function does
not perform any I/O, it simply informs this object that some amount of
its buffer, returned from [`poll_fill_buf`], has been consumed and should
no longer be returned. As such, this function may do odd things if
[`poll_fill_buf`] isn't called before calling it.

The `amt` must be `<=` the number of bytes in the buffer returned by
[`poll_fill_buf`].

[`poll_read`]: AsyncRead::poll_read
[`poll_fill_buf`]: AsyncBufRead::poll_fill_buf

## tokio::create (function)

Creates the named pipe identified by `addr` for use as a server.

This uses the [`CreateNamedPipe`] function.

[`CreateNamedPipe`]: https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createnamedpipea

### tokio::create (function) › Errors

This errors if called outside of a [Tokio Runtime], or in a runtime that
has not [enabled I/O], or if any OS-specific I/O errors occur.

[Tokio Runtime]: crate::runtime::Runtime
[enabled I/O]: crate::runtime::Builder::enable_io

### tokio::create (function) › Examples

```
use tokio::net::windows::named_pipe::ServerOptions;

const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-create";

# #[tokio::main] async fn main() -> std::io::Result<()> {
let server = ServerOptions::new().create(PIPE_NAME)?;
# Ok(()) }
```

## tokio::create (function)

Creates the specified directory with the configured options.

It is considered an error if the directory already exists unless
recursive mode is enabled.

This is an async version of [`std::fs::DirBuilder::create`].

### tokio::create (function) › Errors

An error will be returned under the following circumstances:

* Path already points to an existing file.
* Path already points to an existing directory and the mode is
  non-recursive.
* The calling process doesn't have permissions to create the directory
  or its missing parents.
* Other I/O error occurred.

### tokio::create (function) › Examples

```no_run
use tokio::fs::DirBuilder;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    DirBuilder::new()
        .recursive(true)
        .create("/tmp/foo/bar/baz")
        .await?;

    Ok(())
}
```

## tokio::create (function)

Opens a file in write-only mode.

This function will create a file if it does not exist, and will truncate
it if it does.

See [`OpenOptions`] for more details.

### tokio::create (function) › Errors

Results in an error if called from outside of the Tokio runtime or if
the underlying [`create`] call results in an error.

[`create`]: std::fs::File::create

### tokio::create (function) › Examples

```no_run
use tokio::fs::File;
use tokio::io::AsyncWriteExt;

# async fn dox() -> std::io::Result<()> {
let mut file = File::create("foo.txt").await?;
file.write_all(b"hello, world!").await?;
# Ok(())
# }
```

The [`write_all`] method is defined on the [`AsyncWriteExt`] trait.

[`write_all`]: fn@crate::io::AsyncWriteExt::write_all
[`AsyncWriteExt`]: trait@crate::io::AsyncWriteExt

## tokio::create (function)

Sets the option for creating a new file.

This option indicates whether a new file will be created if the file
does not yet already exist.

In order for the file to be created, [`write`] or [`append`] access must
be used.

This is an async version of [`std::fs::OpenOptions::create`][std]

[std]: std::fs::OpenOptions::create
[`write`]: OpenOptions::write
[`append`]: OpenOptions::append

### tokio::create (function) › Examples

```no_run
use tokio::fs::OpenOptions;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let file = OpenOptions::new()
        .write(true)
        .create(true)
        .open("foo.txt")
        .await?;

    Ok(())
}
```

## tokio::create_new (function)

Opens a file in read-write mode.

This function will create a file if it does not exist, or return an error
if it does. This way, if the call succeeds, the file returned is guaranteed
to be new.

This option is useful because it is atomic. Otherwise between checking
whether a file exists and creating a new one, the file may have been
created by another process (a TOCTOU race condition / attack).

This can also be written using `File::options().read(true).write(true).create_new(true).open(...)`.

See [`OpenOptions`] for more details.

### tokio::create_new (function) › Examples

```no_run
use tokio::fs::File;
use tokio::io::AsyncWriteExt;

# async fn dox() -> std::io::Result<()> {
let mut file = File::create_new("foo.txt").await?;
file.write_all(b"hello, world!").await?;
# Ok(())
# }
```

The [`write_all`] method is defined on the [`AsyncWriteExt`] trait.

[`write_all`]: fn@crate::io::AsyncWriteExt::write_all
[`AsyncWriteExt`]: trait@crate::io::AsyncWriteExt

## tokio::create_new (function)

Sets the option to always create a new file.

This option indicates whether a new file will be created.  No file is
allowed to exist at the target location, also no (dangling) symlink.

This option is useful because it is atomic. Otherwise between checking
whether a file exists and creating a new one, the file may have been
created by another process (a TOCTOU race condition / attack).

If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
ignored.

The file must be opened with write or append access in order to create a
new file.

This is an async version of [`std::fs::OpenOptions::create_new`][std]

[std]: std::fs::OpenOptions::create_new
[`.create()`]: OpenOptions::create
[`.truncate()`]: OpenOptions::truncate

### tokio::create_new (function) › Examples

```no_run
use tokio::fs::OpenOptions;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let file = OpenOptions::new()
        .write(true)
        .create_new(true)
        .open("foo.txt")
        .await?;

    Ok(())
}
```

## tokio::create_with_security_attributes_raw (function)

Creates the named pipe identified by `addr` for use as a server.

This is the same as [`create`] except that it supports providing the raw
pointer to a structure of [`SECURITY_ATTRIBUTES`] which will be passed
as the `lpSecurityAttributes` argument to [`CreateFile`].

### tokio::create_with_security_attributes_raw (function) › Errors

This errors if called outside of a [Tokio Runtime], or in a runtime that
has not [enabled I/O], or if any OS-specific I/O errors occur.

[Tokio Runtime]: crate::runtime::Runtime
[enabled I/O]: crate::runtime::Builder::enable_io

### tokio::create_with_security_attributes_raw (function) › Safety

The `attrs` argument must either be null or point at a valid instance of
the [`SECURITY_ATTRIBUTES`] structure. If the argument is null, the
behavior is identical to calling the [`create`] method.

[`create`]: ServerOptions::create
[`CreateFile`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew
[`SECURITY_ATTRIBUTES`]: https://docs.rs/windows-sys/latest/windows_sys/Win32/Security/struct.SECURITY_ATTRIBUTES.html

## tokio::creation_flags (function)

Sets the [process creation flags][1] to be passed to `CreateProcess`.

These will always be ORed with `CREATE_UNICODE_ENVIRONMENT`.

[1]: https://msdn.microsoft.com/en-us/library/windows/desktop/ms684863(v=vs.85).aspx

## tokio::current (function)

Returns a `Handle` view over the currently running `Runtime`.

### tokio::current (function) › Panics

This will panic if called outside the context of a Tokio runtime. That means that you must
call this on one of the threads **being run by the runtime**, or from a thread with an active
`EnterGuard`. Calling this from within a thread created by `std::thread::spawn` (for example)
will cause a panic unless that thread has an active `EnterGuard`.

### tokio::current (function) › Examples

This can be used to obtain the handle of the surrounding runtime from an async
block or function running on that runtime.

```
# #[cfg(not(target_family = "wasm"))]
# {
# use std::thread;
# use tokio::runtime::Runtime;
# fn dox() {
# let rt = Runtime::new().unwrap();
# rt.spawn(async {
use tokio::runtime::Handle;

// Inside an async block or function.
let handle = Handle::current();
handle.spawn(async {
    println!("now running in the existing Runtime");
});

# let handle =
thread::spawn(move || {
    // Notice that the handle is created outside of this thread and then moved in
    handle.spawn(async { /* ... */ });
    // This next line would cause a panic because we haven't entered the runtime
    // and created an EnterGuard
    // let handle2 = Handle::current(); // panic
    // So we create a guard here with Handle::enter();
    let _guard = handle.enter();
    // Now we can call Handle::current();
    let handle2 = Handle::current();
});
# handle.join().unwrap();
# });
# }
# }
```

## tokio::current_dir (function)

Sets the working directory for the child process.

### tokio::current_dir (function) › Platform-specific behavior

If the program path is relative (e.g., `"./script.sh"`), it's ambiguous
whether it should be interpreted relative to the parent's working
directory or relative to `current_dir`. The behavior in this case is
platform specific and unstable, and it's recommended to use
[`canonicalize`] to get an absolute program path instead.

[`canonicalize`]: crate::fs::canonicalize()

### tokio::current_dir (function) › Examples

Basic usage:

```no_run
# async fn test() { // allow using await
use tokio::process::Command;

let output = Command::new("ls")
        .current_dir("/bin")
        .output().await.unwrap();
# }
```

## tokio::custom_flags (function)

Passes custom flags to the `flags` argument of `open`.

The bits that define the access mode are masked out with `O_ACCMODE`, to
ensure they do not interfere with the access mode set by Rusts options.

Custom flags can only set flags, not remove flags set by Rusts options.
This options overwrites any previously set custom flags.

### tokio::custom_flags (function) › Examples

```no_run
use tokio::fs::OpenOptions;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let mut options = OpenOptions::new();
    options.write(true);
    if cfg!(unix) {
        options.custom_flags(libc::O_NOFOLLOW);
    }
    let file = options.open("foo.txt").await?;

    Ok(())
}
```

## tokio::custom_flags (function)

Sets extra flags for the `dwFileFlags` argument to the call to
[`CreateFile2`] to the specified value (or combines it with
`attributes` and `security_qos_flags` to set the `dwFlagsAndAttributes`
for [`CreateFile`]).

Custom flags can only set flags, not remove flags set by Rust's options.
This option overwrites any previously set custom flags.

### tokio::custom_flags (function) › Examples

```no_run
use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_DELETE_ON_CLOSE;
use tokio::fs::OpenOptions;

# #[tokio::main]
# async fn main() -> std::io::Result<()> {
let file = OpenOptions::new()
    .create(true)
    .write(true)
    .custom_flags(FILE_FLAG_DELETE_ON_CLOSE)
    .open("foo.txt").await?;
# Ok(())
# }
```

[`CreateFile`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea
[`CreateFile2`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfile2

## tokio::datagram (function)

Converts the socket into a [`UnixDatagram`].

Calling this function on a socket created by [`new_stream`] will return an error.

[`new_stream`]: `UnixSocket::new_stream`

## tokio::deadline (function)

Returns the instant at which the future will complete.

## tokio::default (function)

Returns [`MissedTickBehavior::Burst`].

For most usecases, the [`Burst`] strategy is what is desired.
Additionally, to preserve backwards compatibility, the [`Burst`]
strategy must be the default. For these reasons,
[`MissedTickBehavior::Burst`] is the default for [`MissedTickBehavior`].
See [`Burst`] for more details.

[`Burst`]: MissedTickBehavior::Burst

## tokio::deregister (function)

Deregisters this AIO event source with Tokio's reactor.

## tokio::detach_all (function)

Removes all tasks from this `JoinSet` without aborting them.

The tasks removed by this call will continue to run in the background even if the `JoinSet`
is dropped.

## tokio::device (function)

Gets the value for the `SO_BINDTODEVICE` option on this socket

This value gets the socket binded device's interface name.

## tokio::device (function)

Gets the value for the `SO_BINDTODEVICE` option on this socket

This value gets the socket-bound device's interface name.

## tokio::disable_lifo_slot (function)

Disables the LIFO task scheduler heuristic.

The multi-threaded scheduler includes a heuristic for optimizing
message-passing patterns. This heuristic results in the **last**
scheduled task being polled first.

To implement this heuristic, each worker thread has a slot which
holds the task that should be polled next. However, this slot cannot
be stolen by other worker threads, which can result in lower total
throughput when tasks tend to have longer poll times.

This configuration option will disable this heuristic resulting in
all scheduled tasks being pushed into the worker-local queue, which
is stealable.

Consider trying this option when the task "scheduled" time is high
but the runtime is underutilized. Use [tokio-rs/tokio-metrics] to
collect this data.

### tokio::disable_lifo_slot (function) › Unstable

This configuration option is considered a workaround for the LIFO
slot not being stealable. When the slot becomes stealable, we will
revisit whether or not this option is necessary. See
issue [tokio-rs/tokio#4941].

### tokio::disable_lifo_slot (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime;

let rt = runtime::Builder::new_multi_thread()
    .disable_lifo_slot()
    .build()
    .unwrap();
# }
```

[tokio-rs/tokio-metrics]: https://github.com/tokio-rs/tokio-metrics
[tokio-rs/tokio#4941]: https://github.com/tokio-rs/tokio/issues/4941

## tokio::disconnect (function)

Disconnects the server end of a named pipe instance from a client
process.

```
use tokio::io::AsyncWriteExt;
use tokio::net::windows::named_pipe::{ClientOptions, ServerOptions};
use windows_sys::Win32::Foundation::ERROR_PIPE_NOT_CONNECTED;

const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-disconnect";

# #[tokio::main] async fn main() -> std::io::Result<()> {
let server = ServerOptions::new()
    .create(PIPE_NAME)?;

let mut client = ClientOptions::new()
    .open(PIPE_NAME)?;

// Wait for a client to become connected.
server.connect().await?;

// Forcibly disconnect the client.
server.disconnect()?;

// Write fails with an OS-specific error after client has been
// disconnected.
let e = client.write(b"ping").await.unwrap_err();
assert_eq!(e.raw_os_error(), Some(ERROR_PIPE_NOT_CONNECTED as i32));
# Ok(()) }
```

## tokio::doc::NotDefinedHere (enum)

The name of a type which is not defined here.

This is typically used as an alias for another type, like so:

```rust,ignore
/// See [some::other::location](https://example.com).
type DEFINED_ELSEWHERE = crate::doc::NotDefinedHere;
```

This type is uninhabitable like the [`never` type] to ensure that no one
will ever accidentally use it.

[`never` type]: https://doc.rust-lang.org/std/primitive.never.html

## tokio::doc::os::windows::io::AsHandle (trait)

See [`std::os::windows::io::AsHandle`](https://doc.rust-lang.org/std/os/windows/io/trait.AsHandle.html)

## tokio::doc::os::windows::io::AsRawHandle (trait)

See [`std::os::windows::io::AsRawHandle`](https://doc.rust-lang.org/std/os/windows/io/trait.AsRawHandle.html)

## tokio::doc::os::windows::io::AsRawSocket (trait)

See [`std::os::windows::io::AsRawSocket`](https://doc.rust-lang.org/std/os/windows/io/trait.AsRawSocket.html)

## tokio::doc::os::windows::io::AsSocket (trait)

See [`std::os::windows::io::AsSocket`](https://doc.rust-lang.org/std/os/windows/io/trait.AsSocket.html)

## tokio::doc::os::windows::io::BorrowedHandle (type_alias)

See [`std::os::windows::io::BorrowedHandle`](https://doc.rust-lang.org/std/os/windows/io/struct.BorrowedHandle.html)

## tokio::doc::os::windows::io::BorrowedSocket (type_alias)

See [`std::os::windows::io::BorrowedSocket`](https://doc.rust-lang.org/std/os/windows/io/struct.BorrowedSocket.html)

## tokio::doc::os::windows::io::FromRawHandle (trait)

See [`std::os::windows::io::FromRawHandle`](https://doc.rust-lang.org/std/os/windows/io/trait.FromRawHandle.html)

## tokio::doc::os::windows::io::FromRawSocket (trait)

See [`std::os::windows::io::FromRawSocket`](https://doc.rust-lang.org/std/os/windows/io/trait.FromRawSocket.html)

## tokio::doc::os::windows::io::IntoRawSocket (trait)

See [`std::os::windows::io::IntoRawSocket`](https://doc.rust-lang.org/std/os/windows/io/trait.IntoRawSocket.html)

## tokio::doc::os::windows::io::OwnedHandle (type_alias)

See [`std::os::windows::io::OwnedHandle`](https://doc.rust-lang.org/std/os/windows/io/struct.OwnedHandle.html)

## tokio::doc::os::windows::io::RawHandle (type_alias)

See [`std::os::windows::io::RawHandle`](https://doc.rust-lang.org/std/os/windows/io/type.RawHandle.html)

## tokio::doc::os::windows::io::RawSocket (type_alias)

See [`std::os::windows::io::RawSocket`](https://doc.rust-lang.org/std/os/windows/io/type.RawSocket.html)

## tokio::downgrade (function)

Atomically downgrades a write lock into a read lock without allowing
any writers to take exclusive access of the lock in the meantime.

**Note:** This won't *necessarily* allow any additional readers to acquire
locks, since [`RwLock`] is fair and it is possible that a writer is next
in line.

Returns an RAII guard which will drop this read access of the `RwLock`
when dropped.

### tokio::downgrade (function) › Examples

```
# use tokio::sync::RwLock;
# use std::sync::Arc;
#
# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let lock = Arc::new(RwLock::new(1));

let n = lock.clone().write_owned().await;

let cloned_lock = lock.clone();
let handle = tokio::spawn(async move {
    *cloned_lock.write_owned().await = 2;
});

let n = n.downgrade();
assert_eq!(*n, 1, "downgrade is atomic");

drop(n);
handle.await.unwrap();
assert_eq!(*lock.read().await, 2, "second writer obtained write lock");
# }
```

## tokio::downgrade (function)

Atomically downgrades a write lock into a read lock without allowing
any writers to take exclusive access of the lock in the meantime.

**Note:** This won't *necessarily* allow any additional readers to acquire
locks, since [`RwLock`] is fair and it is possible that a writer is next
in line.

Returns an RAII guard which will drop this read access of the `RwLock`
when dropped.

### tokio::downgrade (function) › Examples

```
# use tokio::sync::RwLock;
# use std::sync::Arc;
#
# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let lock = Arc::new(RwLock::new(1));

let n = lock.write().await;

let cloned_lock = lock.clone();
let handle = tokio::spawn(async move {
    *cloned_lock.write().await = 2;
});

let n = n.downgrade();
assert_eq!(*n, 1, "downgrade is atomic");

drop(n);
handle.await.unwrap();
assert_eq!(*lock.read().await, 2, "second writer obtained write lock");
# }
```

[`RwLock`]: struct@crate::sync::RwLock

## tokio::downgrade (function)

Converts the `Sender` to a [`WeakSender`] that does not count
towards RAII semantics, i.e. if all `Sender` instances of the
channel were dropped and only `WeakSender` instances remain,
the channel is closed.

## tokio::downgrade (function)

Converts the `Sender` to a [`WeakSender`] that does not count
towards RAII semantics, i.e. if all `Sender` instances of the
channel were dropped and only `WeakSender` instances remain,
the channel is closed.

## tokio::downgrade (function)

Converts the `UnboundedSender` to a [`WeakUnboundedSender`] that does not count
towards RAII semantics, i.e. if all `UnboundedSender` instances of the
channel were dropped and only `WeakUnboundedSender` instances remain,
the channel is closed.

## tokio::downgrade_map (function)

Makes a new [`OwnedRwLockReadGuard`] for a component of the locked data.

This operation cannot fail as the `OwnedRwLockWriteGuard` passed in already
locked the data.

This is an associated function that needs to be used as
`OwnedRwLockWriteGuard::downgrade_map(..)`. A method would interfere with methods of
the same name on the contents of the locked data.

Inside of `f`, you retain exclusive access to the data, despite only being given a `&T`. Handing out a
`&mut T` would result in unsoundness, as you could use interior mutability.

### tokio::downgrade_map (function) › Examples

```
use std::sync::Arc;
use tokio::sync::{RwLock, OwnedRwLockWriteGuard};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Foo(u32);

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let lock = Arc::new(RwLock::new(Foo(1)));

let guard = Arc::clone(&lock).write_owned().await;
let mapped = OwnedRwLockWriteGuard::downgrade_map(guard, |f| &f.0);
let foo = lock.read_owned().await;
assert_eq!(foo.0, *mapped);
# }
```

## tokio::downgrade_map (function)

Makes a new [`RwLockReadGuard`] for a component of the locked data.

This operation cannot fail as the `RwLockWriteGuard` passed in already
locked the data.

This is an associated function that needs to be used as
`RwLockWriteGuard::downgrade_map(..)`. A method would interfere with methods of
the same name on the contents of the locked data.

This is equivalent to a combination of asynchronous [`RwLockWriteGuard::map`] and [`RwLockWriteGuard::downgrade`]
from the [`parking_lot` crate].

Inside of `f`, you retain exclusive access to the data, despite only being given a `&T`. Handing out a
`&mut T` would result in unsoundness, as you could use interior mutability.

[`RwLockMappedWriteGuard`]: struct@crate::sync::RwLockMappedWriteGuard
[`RwLockWriteGuard::map`]: https://docs.rs/lock_api/latest/lock_api/struct.RwLockWriteGuard.html#method.map
[`RwLockWriteGuard::downgrade`]: https://docs.rs/lock_api/latest/lock_api/struct.RwLockWriteGuard.html#method.downgrade
[`parking_lot` crate]: https://crates.io/crates/parking_lot

### tokio::downgrade_map (function) › Examples

```
use tokio::sync::{RwLock, RwLockWriteGuard};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Foo(u32);

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let lock = RwLock::new(Foo(1));

let mapped = RwLockWriteGuard::downgrade_map(lock.write().await, |f| &f.0);
let foo = lock.read().await;
assert_eq!(foo.0, *mapped);
# }
```

## tokio::dump (function)

Captures a snapshot of the runtime's state.

If you only want to capture a snapshot of a single future's state, you can use
[`Trace::capture`][crate::runtime::dump::Trace].

This functionality is experimental, and comes with a number of
requirements and limitations.

### tokio::dump (function) › Examples

This can be used to get call traces of each task in the runtime.
Calls to `Handle::dump` should usually be enclosed in a
[timeout][crate::time::timeout], so that dumping does not escalate a
single blocked runtime thread into an entirely blocked runtime.

```
# use tokio::runtime::Runtime;
# fn dox() {
# let rt = Runtime::new().unwrap();
# rt.spawn(async {
use tokio::runtime::Handle;
use tokio::time::{timeout, Duration};

// Inside an async block or function.
let handle = Handle::current();
if let Ok(dump) = timeout(Duration::from_secs(2), handle.dump()).await {
    for (i, task) in dump.tasks().iter().enumerate() {
        let trace = task.trace();
        println!("TASK {i}:");
        println!("{trace}\n");
    }
}
# });
# }
```

This produces highly detailed traces of tasks; e.g.:

```plain
TASK 0:
╼ dump::main::{{closure}}::a::{{closure}} at /tokio/examples/dump.rs:18:20
└╼ dump::main::{{closure}}::b::{{closure}} at /tokio/examples/dump.rs:23:20
   └╼ dump::main::{{closure}}::c::{{closure}} at /tokio/examples/dump.rs:28:24
      └╼ tokio::sync::barrier::Barrier::wait::{{closure}} at /tokio/tokio/src/sync/barrier.rs:129:10
         └╼ <tokio::util::trace::InstrumentedAsyncOp<F> as core::future::future::Future>::poll at /tokio/tokio/src/util/trace.rs:77:46
            └╼ tokio::sync::barrier::Barrier::wait_internal::{{closure}} at /tokio/tokio/src/sync/barrier.rs:183:36
               └╼ tokio::sync::watch::Receiver<T>::changed::{{closure}} at /tokio/tokio/src/sync/watch.rs:604:55
                  └╼ tokio::sync::watch::changed_impl::{{closure}} at /tokio/tokio/src/sync/watch.rs:755:18
                     └╼ <tokio::sync::notify::Notified as core::future::future::Future>::poll at /tokio/tokio/src/sync/notify.rs:1103:9
                        └╼ tokio::sync::notify::Notified::poll_notified at /tokio/tokio/src/sync/notify.rs:996:32
```

### tokio::dump (function) › Requirements

### tokio::dump (function) › Debug Info Must Be Available

To produce task traces, the application must **not** be compiled
with `split debuginfo`. On Linux, including `debuginfo` within the
application binary is the (correct) default. You can further ensure
this behavior with the following directive in your `Cargo.toml`:

```toml
[profile.*]
split-debuginfo = "off"
```

### tokio::dump (function) › Unstable Features

This functionality is **unstable**, and requires both the
`--cfg tokio_unstable` and cargo feature `taskdump` to be set.

You can do this by setting the `RUSTFLAGS` environment variable
before invoking `cargo`; e.g.:
```bash
RUSTFLAGS="--cfg tokio_unstable" cargo run --example dump
```

Or by [configuring][cargo-config] `rustflags` in
`.cargo/config.toml`:
```text
[build]
rustflags = ["--cfg", "tokio_unstable"]
```

[cargo-config]:
    https://doc.rust-lang.org/cargo/reference/config.html

### tokio::dump (function) › Platform Requirements

Task dumps are supported on Linux atop `aarch64`, `x86`, `x86_64` and `s390x`.

### tokio::dump (function) › Current Thread Runtime Requirements

On the `current_thread` runtime, task dumps may only be requested
from *within* the context of the runtime being dumped. Do not, for
example, await `Handle::dump()` on a different runtime.

### tokio::dump (function) › Limitations

### tokio::dump (function) › Performance

Although enabling the `taskdump` feature imposes virtually no
additional runtime overhead, actually calling `Handle::dump` is
expensive. The runtime must synchronize and pause its workers, then
re-poll every task in a special tracing mode. Avoid requesting dumps
often.

### tokio::dump (function) › Local Executors

Tasks managed by local executors (e.g., `FuturesUnordered` and
[`LocalSet`][crate::task::LocalSet]) may not appear in task dumps.

### tokio::dump (function) › Non-Termination When Workers Are Blocked

The future produced by `Handle::dump` may never produce `Ready` if
another runtime worker is blocked for more than 250ms. This may
occur if a dump is requested during shutdown, or if another runtime
worker is infinite looping or synchronously deadlocked. For these
reasons, task dumping should usually be paired with an explicit
[timeout][crate::time::timeout].

## tokio::duration_since (function)

Returns the amount of time elapsed from another instant to this one, or
zero duration if that instant is later than this one.

## tokio::elapsed (function)

Returns the amount of time elapsed since this instant was created,
or zero duration if this instant is in the future.

### tokio::elapsed (function) › Examples

```
use tokio::time::{Duration, Instant, sleep};

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let instant = Instant::now();
let three_secs = Duration::from_secs(3);
sleep(three_secs).await;
assert!(instant.elapsed() >= three_secs);
# }
```

## tokio::enable (function)

Adds this future to the list of futures that are ready to receive
wakeups from calls to [`notify_one`].

Polling the future also adds it to the list, so this method should only
be used if you want to add the future to the list before the first call
to `poll`. (In fact, this method is equivalent to calling `poll` except
that no `Waker` is registered.)

This has no effect on notifications sent using [`notify_waiters`], which
are received as long as they happen after the creation of the `Notified`
regardless of whether `enable` or `poll` has been called.

This method returns true if the `Notified` is ready. This happens in the
following situations:

 1. The `notify_waiters` method was called between the creation of the
    `Notified` and the call to this method.
 2. This is the first call to `enable` or `poll` on this future, and the
    `Notify` was holding a permit from a previous call to `notify_one`.
    The call consumes the permit in that case.
 3. The future has previously been enabled or polled, and it has since
    then been marked ready by either consuming a permit from the
    `Notify`, or by a call to `notify_one` or `notify_waiters` that
    removed it from the list of futures ready to receive wakeups.

If this method returns true, any future calls to poll on the same future
will immediately return `Poll::Ready`.

### tokio::enable (function) › Examples

Unbound multi-producer multi-consumer (mpmc) channel.

The call to `enable` is important because otherwise if you have two
calls to `recv` and two calls to `send` in parallel, the following could
happen:

 1. Both calls to `try_recv` return `None`.
 2. Both new elements are added to the vector.
 3. The `notify_one` method is called twice, adding only a single
    permit to the `Notify`.
 4. Both calls to `recv` reach the `Notified` future. One of them
    consumes the permit, and the other sleeps forever.

By adding the `Notified` futures to the list by calling `enable` before
`try_recv`, the `notify_one` calls in step three would remove the
futures from the list and mark them notified instead of adding a permit
to the `Notify`. This ensures that both futures are woken.

```
use tokio::sync::Notify;

use std::collections::VecDeque;
use std::sync::Mutex;

struct Channel<T> {
    messages: Mutex<VecDeque<T>>,
    notify_on_sent: Notify,
}

impl<T> Channel<T> {
    pub fn send(&self, msg: T) {
        let mut locked_queue = self.messages.lock().unwrap();
        locked_queue.push_back(msg);
        drop(locked_queue);

        // Send a notification to one of the calls currently
        // waiting in a call to `recv`.
        self.notify_on_sent.notify_one();
    }

    pub fn try_recv(&self) -> Option<T> {
        let mut locked_queue = self.messages.lock().unwrap();
        locked_queue.pop_front()
    }

    pub async fn recv(&self) -> T {
        let future = self.notify_on_sent.notified();
        tokio::pin!(future);

        loop {
            // Make sure that no wakeup is lost if we get
            // `None` from `try_recv`.
            future.as_mut().enable();

            if let Some(msg) = self.try_recv() {
                return msg;
            }

            // Wait for a call to `notify_one`.
            //
            // This uses `.as_mut()` to avoid consuming the future,
            // which lets us call `Pin::set` below.
            future.as_mut().await;

            // Reset the future in case another call to
            // `try_recv` got the message before us.
            future.set(self.notify_on_sent.notified());
        }
    }
}
```

[`notify_one`]: Notify::notify_one()
[`notify_waiters`]: Notify::notify_waiters()

## tokio::enable (function)

Adds this future to the list of futures that are ready to receive
wakeups from calls to [`notify_one`].

See [`Notified::enable`] for more details.

[`notify_one`]: Notify::notify_one()

## tokio::enable_all (function)

Enables both I/O and time drivers.

Doing this is a shorthand for calling `enable_io` and `enable_time`
individually. If additional components are added to Tokio in the future,
`enable_all` will include these future components.

### tokio::enable_all (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime;

let rt = runtime::Builder::new_multi_thread()
    .enable_all()
    .build()
    .unwrap();
# }
```

## tokio::enable_alt_timer (function)

Enables the alternative timer implementation, which is disabled by default.

The alternative timer implementation is an unstable feature that may
provide better performance on multi-threaded runtimes with a large number
of worker threads.

This option only applies to multi-threaded runtimes. Attempting to use
this option with any other runtime type will have no effect.

[Click here to share your experience with the alternative timer](https://github.com/tokio-rs/tokio/issues/7745)

### tokio::enable_alt_timer (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime;

let rt = runtime::Builder::new_multi_thread()
  .enable_alt_timer()
  .build()
  .unwrap();
# }
```

## tokio::enable_eager_driver_handoff (function)

Enable eager hand-off of the I/O and time drivers for multi-threaded
runtimes, which is disabled by default.

When this option is enabled, a worker thread which has parked on the I/O
or time driver will notify another worker thread once it is preparing to
begin polling a task from the run queue, so that the notified worker can
begin polling the I/O or time driver. This can reduce the latency with
which I/O and timer notifications are processed, especially when some
tasks have polls that take a long time to complete. In addition, it can
reduce the risk of a deadlock which may occur when a task blocks the
worker thread which is holding the I/O or time driver until some other
task, which is waiting for a notification from *that* driver, unblocks
it.

This option is disabled by default, as enabling it may potentially
increase contention due to extra synchronization in cross-driver
wakeups.

This option only applies to multi-threaded runtimes. Attempting to use
this option with any other runtime type will have no effect.

**Note**: This is an [unstable API][unstable]. Eager driver hand-off is
an experimental feature whose behavior may be removed or changed in 1.x
releases. See [the documentation on unstable features][unstable] for
details.

[unstable]: crate#unstable-features

## tokio::enable_io (function)

Enables the I/O driver.

Doing this enables using net, process, signal, and some I/O types on
the runtime.

### tokio::enable_io (function) › Examples

```
use tokio::runtime;

let rt = runtime::Builder::new_multi_thread()
    .enable_io()
    .build()
    .unwrap();
```

## tokio::enable_io_uring (function)

Enables the tokio's io_uring driver.

Doing this enables using io_uring operations on the runtime.

### tokio::enable_io_uring (function) › Examples

```
use tokio::runtime;

let rt = runtime::Builder::new_multi_thread()
    .enable_io_uring()
    .build()
    .unwrap();
```

## tokio::enable_metrics_poll_time_histogram (function)

Enables tracking the distribution of task poll times.

Task poll times are not instrumented by default as doing so requires
calling [`Instant::now()`] twice per task poll, which could add
measurable overhead. Use the [`Handle::metrics()`] to access the
metrics data.

The histogram uses fixed bucket sizes. In other words, the histogram
buckets are not dynamic based on input values. Use the
`metrics_poll_time_histogram` builder methods to configure the
histogram details.

By default, a linear histogram with 10 buckets each 100 microseconds wide will be used.
This has an extremely low memory footprint, but may not provide enough granularity. For
better granularity with low memory usage, use [`metrics_poll_time_histogram_configuration()`]
to select [`LogHistogram`] instead.

### tokio::enable_metrics_poll_time_histogram (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime;

let rt = runtime::Builder::new_multi_thread()
    .enable_metrics_poll_time_histogram()
    .build()
    .unwrap();
# // Test default values here
# fn us(n: u64) -> std::time::Duration { std::time::Duration::from_micros(n) }
# let m = rt.handle().metrics();
# assert_eq!(m.poll_time_histogram_num_buckets(), 10);
# assert_eq!(m.poll_time_histogram_bucket_range(0), us(0)..us(100));
# assert_eq!(m.poll_time_histogram_bucket_range(1), us(100)..us(200));
# }
```

[`Handle::metrics()`]: crate::runtime::Handle::metrics
[`Instant::now()`]: std::time::Instant::now
[`LogHistogram`]: crate::runtime::LogHistogram
[`metrics_poll_time_histogram_configuration()`]: Builder::metrics_poll_time_histogram_configuration

## tokio::enable_metrics_schedule_latency_histogram (function)

Enables tracking the distribution of task schedule latencies. Task
schedule latency is the time between when a task is scheduled for
execution and when it is polled.

**This feature is only supported on 64-bit targets.**

Task schedule latencies are not instrumented by default as doing
so requires calling [`Instant::now()`] when a task is scheduled
and when it is polled, which could add measurable overhead. Use
the [`Handle::metrics()`] to access the metrics data.

By default, a linear histogram with 10 buckets each 100 microseconds wide will be used.
This has an extremely low memory footprint, but may not provide enough granularity. For
better granularity with low memory usage, use [`metrics_schedule_latency_histogram_configuration()`]
to select [`LogHistogram`] instead.

### tokio::enable_metrics_schedule_latency_histogram (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime;

let rt = runtime::Builder::new_multi_thread()
    .enable_metrics_schedule_latency_histogram()
    .build()
    .unwrap();
# // Test default values here
# fn us(n: u64) -> std::time::Duration { std::time::Duration::from_micros(n) }
# let m = rt.handle().metrics();
# assert_eq!(m.schedule_latency_histogram_num_buckets(), 10);
# assert_eq!(m.schedule_latency_histogram_bucket_range(0), us(0)..us(100));
# assert_eq!(m.schedule_latency_histogram_bucket_range(1), us(100)..us(200));
# }
```

[`Handle::metrics()`]: crate::runtime::Handle::metrics
[`Instant::now()`]: std::time::Instant::now
[`LogHistogram`]: crate::runtime::LogHistogram
[`metrics_schedule_latency_histogram_configuration()`]: Builder::metrics_schedule_latency_histogram_configuration

## tokio::enable_time (function)

Enables the time driver.

Doing this enables using `tokio::time` on the runtime.

### tokio::enable_time (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime;

let rt = runtime::Builder::new_multi_thread()
    .enable_time()
    .build()
    .unwrap();
# }
```

## tokio::end (struct_field)

Indicates the end of a named pipe.

## tokio::enter (function)

Enters the context of this `LocalSet`.

The [`spawn_local`] method will spawn tasks on the `LocalSet` whose
context you are inside.

[`spawn_local`]: fn@crate::task::spawn_local

## tokio::enter (function)

Enters the runtime context.

This allows you to construct types that must have an executor
available on creation such as [`Sleep`] or [`TcpStream`]. It will
also allow you to call methods such as [`tokio::spawn`].

If this is a handle to a [`LocalRuntime`], and this function is being invoked from the same
thread that the runtime was created on, you will also be able to call
[`tokio::task::spawn_local`].

[`Sleep`]: struct@crate::time::Sleep
[`TcpStream`]: struct@crate::net::TcpStream
[`tokio::spawn`]: fn@crate::spawn
[`LocalRuntime`]: struct@crate::runtime::LocalRuntime
[`tokio::task::spawn_local`]: fn@crate::task::spawn_local

### tokio::enter (function) › Example

```
use tokio::runtime::LocalRuntime;
use tokio::task::JoinHandle;

fn function_that_spawns(msg: String) -> JoinHandle<()> {
    // Had we not used `rt.enter` below, this would panic.
    tokio::spawn(async move {
        println!("{}", msg);
    })
}

fn main() {
    let rt = LocalRuntime::new().unwrap();

    let s = "Hello World!".to_string();

    // By entering the context, we tie `tokio::spawn` to this executor.
    let _guard = rt.enter();
    let handle = function_that_spawns(s);

    // Wait for the task before we end the test.
    rt.block_on(handle).unwrap();
}
```

## tokio::enter (function)

Enters the runtime context.

This allows you to construct types that must have an executor
available on creation such as [`Sleep`] or [`TcpStream`]. It will
also allow you to call methods such as [`tokio::spawn`].

[`Sleep`]: struct@crate::time::Sleep
[`TcpStream`]: struct@crate::net::TcpStream
[`tokio::spawn`]: fn@crate::spawn

### tokio::enter (function) › Example

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime::Runtime;
use tokio::task::JoinHandle;

fn function_that_spawns(msg: String) -> JoinHandle<()> {
    // Had we not used `rt.enter` below, this would panic.
    tokio::spawn(async move {
        println!("{}", msg);
    })
}

fn main() {
    let rt = Runtime::new().unwrap();

    let s = "Hello World!".to_string();

    // By entering the context, we tie `tokio::spawn` to this executor.
    let _guard = rt.enter();
    let handle = function_that_spawns(s);

    // Wait for the task before we end the test.
    rt.block_on(handle).unwrap();
}
# }
```

## tokio::enter (function)

Enters the runtime context. This allows you to construct types that must
have an executor available on creation such as [`Sleep`] or
[`TcpStream`]. It will also allow you to call methods such as
[`tokio::spawn`] and [`Handle::current`] without panicking.

### tokio::enter (function) › Panics

When calling `Handle::enter` multiple times, the returned guards
**must** be dropped in the reverse order that they were acquired.
Failure to do so will result in a panic and possible memory leaks.

### tokio::enter (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime::Runtime;

let rt = Runtime::new().unwrap();

let _guard = rt.enter();
tokio::spawn(async {
    println!("Hello world!");
});
# }
```

Do **not** do the following, this shows a scenario that will result in a
panic and possible memory leak.

```should_panic,ignore-wasm
use tokio::runtime::Runtime;

let rt1 = Runtime::new().unwrap();
let rt2 = Runtime::new().unwrap();

let enter1 = rt1.enter();
let enter2 = rt2.enter();

drop(enter1);
drop(enter2);
```

[`Sleep`]: struct@crate::time::Sleep
[`TcpStream`]: struct@crate::net::TcpStream
[`tokio::spawn`]: fn@crate::spawn

## tokio::env (function)

Inserts or updates an environment variable mapping.

Note that environment variable names are case-insensitive (but case-preserving) on Windows,
and case-sensitive on all other platforms.

### tokio::env (function) › Examples

Basic usage:

```no_run
# async fn test() { // allow using await
use tokio::process::Command;

let output = Command::new("ls")
        .env("PATH", "/bin")
        .output().await.unwrap();
# }
```

## tokio::env_clear (function)

Clears the entire environment map for the child process.

### tokio::env_clear (function) › Examples

Basic usage:

```no_run
# async fn test() { // allow using await
use tokio::process::Command;

let output = Command::new("ls")
        .env_clear()
        .output().await.unwrap();
# }
```

## tokio::env_remove (function)

Removes an environment variable mapping.

### tokio::env_remove (function) › Examples

Basic usage:

```no_run
# async fn test() { // allow using await
use tokio::process::Command;

let output = Command::new("ls")
        .env_remove("PATH")
        .output().await.unwrap();
# }
```

## tokio::envs (function)

Adds or updates multiple environment variable mappings.

### tokio::envs (function) › Examples

Basic usage:

```no_run
# async fn test() { // allow using await
use tokio::process::Command;
use std::process::{Stdio};
use std::env;
use std::collections::HashMap;

let filtered_env : HashMap<String, String> =
    env::vars().filter(|&(ref k, _)|
        k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
    ).collect();

let output = Command::new("printenv")
        .stdin(Stdio::null())
        .stdout(Stdio::inherit())
        .env_clear()
        .envs(&filtered_env)
        .output().await.unwrap();
# }
```

## tokio::event_interval (function)

Sets the number of scheduler ticks after which the scheduler will poll for
external events (timers, I/O, and so on).

A scheduler "tick" roughly corresponds to one `poll` invocation on a task.

By default, the event interval is `61` for all scheduler types.

Setting the event interval determines the effective "priority" of delivering
these external events (which may wake up additional tasks), compared to
executing tasks that are currently ready to run. A smaller value is useful
when tasks frequently spend a long time in polling, or infrequently yield,
which can result in overly long delays picking up I/O events. Conversely,
picking up new events requires extra synchronization and syscall overhead,
so if tasks generally complete their polling quickly, a higher event interval
will minimize that overhead while still keeping the scheduler responsive to
events.

### tokio::event_interval (function) › Panics

This function will panic if 0 is passed as an argument.

### tokio::event_interval (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
# use tokio::runtime;
# pub fn main() {
let rt = runtime::Builder::new_multi_thread()
    .event_interval(31)
    .build();
# }
# }
```

## tokio::file_name (function)

Returns the bare file name of this directory entry without any other
leading path component.

### tokio::file_name (function) › Examples

```
use tokio::fs;

# async fn dox() -> std::io::Result<()> {
let mut entries = fs::read_dir(".").await?;

while let Some(entry) = entries.next_entry().await? {
    println!("{:?}", entry.file_name());
}
# Ok(())
# }
```

## tokio::file_type (function)

Returns the file type for the file that this entry points at.

This function will not traverse symlinks if this entry points at a
symlink.

### tokio::file_type (function) › Platform-specific behavior

On Windows and most Unix platforms this function is free (no extra
system calls needed), but some Unix platforms may require the equivalent
call to `symlink_metadata` to learn about the target file type.

### tokio::file_type (function) › Examples

```
use tokio::fs;

# async fn dox() -> std::io::Result<()> {
let mut entries = fs::read_dir(".").await?;

while let Some(entry) = entries.next_entry().await? {
    if let Ok(file_type) = entry.file_type().await {
        // Now let's show our entry's file type!
        println!("{:?}: {:?}", entry.path(), file_type);
    } else {
        println!("Couldn't get file type for {:?}", entry.path());
    }
}
# Ok(())
# }
```

## tokio::filename (function)

Returns the file name where this function was defined. If debuginfo
is missing, this is likely to return None.

## tokio::fill_buf (function)

Returns the contents of the internal buffer, filling it with more
data from the inner reader if it is empty.

This function is a lower-level call. It needs to be paired with the
[`consume`] method to function properly. When calling this method,
none of the contents will be "read" in the sense that later calling
`read` may return the same contents. As such, [`consume`] must be
called with the number of bytes that are consumed from this buffer
to ensure that the bytes are never returned twice.

An empty buffer returned indicates that the stream has reached EOF.

Equivalent to:

```ignore
async fn fill_buf(&mut self) -> io::Result<&[u8]>;
```

### tokio::fill_buf (function) › Errors

This function will return an I/O error if the underlying reader was
read, but returned an error.

### tokio::fill_buf (function) › Cancel safety

This method is cancel safe. If used as a branch in
[`tokio::select!`](crate::select) and another branch
completes first, then it is guaranteed that no data was read.

[`consume`]: crate::io::AsyncBufReadExt::consume

## tokio::filled (function)

Returns a shared reference to the filled portion of the buffer.

## tokio::filled_mut (function)

Returns a mutable reference to the filled portion of the buffer.

## tokio::first_pipe_instance (function)

If you attempt to create multiple instances of a pipe with this flag
set, creation of the first server instance succeeds, but creation of any
subsequent instances will fail with
[`std::io::ErrorKind::PermissionDenied`].

This option is intended to be used with servers that want to ensure that
they are the only process listening for clients on a given named pipe.
This is accomplished by enabling it for the first server instance
created in a process.

This corresponds to setting [`FILE_FLAG_FIRST_PIPE_INSTANCE`].

### tokio::first_pipe_instance (function) › Errors

If this option is set and more than one instance of the server for a
given named pipe exists, calling [`create`] will fail with
[`std::io::ErrorKind::PermissionDenied`].

```
use std::io;
use tokio::net::windows::named_pipe::ServerOptions;

const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-first-instance-error";

# #[tokio::main] async fn main() -> io::Result<()> {
let server1 = ServerOptions::new()
    .first_pipe_instance(true)
    .create(PIPE_NAME)?;

// Second server errs, since it's not the first instance.
let e = ServerOptions::new()
    .first_pipe_instance(true)
    .create(PIPE_NAME)
    .unwrap_err();

assert_eq!(e.kind(), io::ErrorKind::PermissionDenied);
# Ok(()) }
```

### tokio::first_pipe_instance (function) › Examples

```
use std::io;
use tokio::net::windows::named_pipe::ServerOptions;

const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-first-instance";

# #[tokio::main] async fn main() -> io::Result<()> {
let mut builder = ServerOptions::new();
builder.first_pipe_instance(true);

let server = builder.create(PIPE_NAME)?;
let e = builder.create(PIPE_NAME).unwrap_err();
assert_eq!(e.kind(), io::ErrorKind::PermissionDenied);
drop(server);

// OK: since, we've closed the other instance.
let _server2 = builder.create(PIPE_NAME)?;
# Ok(()) }
```

[`create`]: ServerOptions::create
[`FILE_FLAG_FIRST_PIPE_INSTANCE`]: https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createnamedpipea#pipe_first_pipe_instance

## tokio::flush (function)

Flushes this output stream, ensuring that all intermediately buffered
contents reach their destination.

Equivalent to:

```ignore
async fn flush(&mut self) -> io::Result<()>;
```

### tokio::flush (function) › Errors

It is considered an error if not all bytes could be written due to
I/O errors or EOF being reached.

### tokio::flush (function) › Cancel safety

This method is cancel safe.

If `flush` is used as a branch in [`tokio::select!`](crate::select)
and another branch completes first, then the buffered data in this
`AsyncWrite` may have been partially flushed.
However, it is guaranteed that the buffer is advanced by the amount of
bytes that have been partially flushed.

### tokio::flush (function) › Examples

```no_run
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::io::{self, BufWriter, AsyncWriteExt};
use tokio::fs::File;

#[tokio::main]
async fn main() -> io::Result<()> {
    let f = File::create("foo.txt").await?;
    let mut buffer = BufWriter::new(f);

    buffer.write_all(b"some bytes").await?;
    buffer.flush().await?;
    Ok(())
}
# }
```

## tokio::forget (function)

Destroys the write half, but don't close the write half of the stream
until the read half is dropped. If the read half has already been
dropped, this closes the stream.

## tokio::forget (function)

Destroys the write half, but don't close the write half of the stream
until the read half is dropped. If the read half has already been
dropped, this closes the stream.

## tokio::forget (function)

Forgets the permit **without** releasing it back to the semaphore.
This can be used to reduce the amount of permits available from a
semaphore.

### tokio::forget (function) › Examples

```
use std::sync::Arc;
use tokio::sync::Semaphore;

let sem = Arc::new(Semaphore::new(10));
{
    let permit = sem.clone().try_acquire_many_owned(5).unwrap();
    assert_eq!(sem.available_permits(), 5);
    permit.forget();
}

// Since we forgot the permit, available permits won't go back to its initial value
// even after the permit is dropped.
assert_eq!(sem.available_permits(), 5);
```

## tokio::forget (function)

Forgets the permit **without** releasing it back to the semaphore.
This can be used to reduce the amount of permits available from a
semaphore.

### tokio::forget (function) › Examples

```
use std::sync::Arc;
use tokio::sync::Semaphore;

let sem = Arc::new(Semaphore::new(10));
{
    let permit = sem.try_acquire_many(5).unwrap();
    assert_eq!(sem.available_permits(), 5);
    permit.forget();
}

// Since we forgot the permit, available permits won't go back to its initial value
// even after the permit is dropped.
assert_eq!(sem.available_permits(), 5);
```

## tokio::forget_permits (function)

Decrease a semaphore's permits by a maximum of `n`.

If there are insufficient permits and it's not possible to reduce by `n`,
return the number of permits that were actually reduced.

## tokio::frames (function)

Return the frames in this backtrace, innermost (in a task dump,
likely to be a leaf future's poll function) first.

## tokio::from_bytes (function)

Generates a seed from the provided byte slice.

### tokio::from_bytes (function) › Example

```
# use tokio::runtime::RngSeed;
let seed = RngSeed::from_bytes(b"make me a seed");
```

## tokio::from_file (function)

Creates a new `Receiver` from a [`File`].

This function is intended to construct a pipe from a [`File`] representing
a special FIFO file. It will check if the file is a pipe and has read access,
set it in non-blocking mode and perform the conversion.

### tokio::from_file (function) › Errors

Fails with `io::ErrorKind::InvalidInput` if the file is not a pipe or it
does not have read access. Also fails with any standard OS error if it occurs.

### tokio::from_file (function) › Panics

This function panics if it is not called from within a runtime with
IO enabled.

The runtime is usually set implicitly when this function is called
from a future driven by a tokio runtime, otherwise runtime can be set
explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.

## tokio::from_file (function)

Creates a new `Sender` from a [`File`].

This function is intended to construct a pipe from a [`File`] representing
a special FIFO file. It will check if the file is a pipe and has write access,
set it in non-blocking mode and perform the conversion.

### tokio::from_file (function) › Errors

Fails with `io::ErrorKind::InvalidInput` if the file is not a pipe or it
does not have write access. Also fails with any standard OS error if it occurs.

### tokio::from_file (function) › Panics

This function panics if it is not called from within a runtime with
IO enabled.

The runtime is usually set implicitly when this function is called
from a future driven by a tokio runtime, otherwise runtime can be set
explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.

## tokio::from_file_unchecked (function)

Creates a new `Receiver` from a [`File`] without checking pipe properties.

This function is intended to construct a pipe from a File representing
a special FIFO file. The conversion assumes nothing about the underlying
file; it is left up to the user to make sure it is opened with read access,
represents a pipe and is set in non-blocking mode.

### tokio::from_file_unchecked (function) › Examples

```no_run
use tokio::net::unix::pipe;
use std::fs::OpenOptions;
use std::os::unix::fs::{FileTypeExt, OpenOptionsExt};
# use std::error::Error;

const FIFO_NAME: &str = "path/to/a/fifo";

# async fn dox() -> Result<(), Box<dyn Error>> {
let file = OpenOptions::new()
    .read(true)
    .custom_flags(libc::O_NONBLOCK)
    .open(FIFO_NAME)?;
if file.metadata()?.file_type().is_fifo() {
    let rx = pipe::Receiver::from_file_unchecked(file)?;
    /* use the Receiver */
}
# Ok(())
# }
```

### tokio::from_file_unchecked (function) › Panics

This function panics if it is not called from within a runtime with
IO enabled.

The runtime is usually set implicitly when this function is called
from a future driven by a tokio runtime, otherwise runtime can be set
explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.

## tokio::from_file_unchecked (function)

Creates a new `Sender` from a [`File`] without checking pipe properties.

This function is intended to construct a pipe from a File representing
a special FIFO file. The conversion assumes nothing about the underlying
file; it is left up to the user to make sure it is opened with write access,
represents a pipe and is set in non-blocking mode.

### tokio::from_file_unchecked (function) › Examples

```no_run
use tokio::net::unix::pipe;
use std::fs::OpenOptions;
use std::os::unix::fs::{FileTypeExt, OpenOptionsExt};
# use std::error::Error;

const FIFO_NAME: &str = "path/to/a/fifo";

# async fn dox() -> Result<(), Box<dyn Error>> {
let file = OpenOptions::new()
    .write(true)
    .custom_flags(libc::O_NONBLOCK)
    .open(FIFO_NAME)?;
if file.metadata()?.file_type().is_fifo() {
    let tx = pipe::Sender::from_file_unchecked(file)?;
    /* use the Sender */
}
# Ok(())
# }
```

### tokio::from_file_unchecked (function) › Panics

This function panics if it is not called from within a runtime with
IO enabled.

The runtime is usually set implicitly when this function is called
from a future driven by a tokio runtime, otherwise runtime can be set
explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.

## tokio::from_owned_fd (function)

Creates a new `Receiver` from an [`OwnedFd`].

This function is intended to construct a pipe from an [`OwnedFd`] representing
an anonymous pipe or a special FIFO file. It will check if the file descriptor
is a pipe and has read access, set it in non-blocking mode and perform the
conversion.

### tokio::from_owned_fd (function) › Errors

Fails with `io::ErrorKind::InvalidInput` if the file descriptor is not a pipe
or it does not have read access. Also fails with any standard OS error if it
occurs.

### tokio::from_owned_fd (function) › Panics

This function panics if it is not called from within a runtime with
IO enabled.

The runtime is usually set implicitly when this function is called
from a future driven by a tokio runtime, otherwise runtime can be set
explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.

## tokio::from_owned_fd (function)

Creates a new `Sender` from an [`OwnedFd`].

This function is intended to construct a pipe from an [`OwnedFd`] representing
an anonymous pipe or a special FIFO file. It will check if the file descriptor
is a pipe and has write access, set it in non-blocking mode and perform the
conversion.

### tokio::from_owned_fd (function) › Errors

Fails with `io::ErrorKind::InvalidInput` if the file descriptor is not a pipe
or it does not have write access. Also fails with any standard OS error if it
occurs.

### tokio::from_owned_fd (function) › Panics

This function panics if it is not called from within a runtime with
IO enabled.

The runtime is usually set implicitly when this function is called
from a future driven by a tokio runtime, otherwise runtime can be set
explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.

## tokio::from_owned_fd_unchecked (function)

Creates a new `Receiver` from an [`OwnedFd`] without checking pipe properties.

This function is intended to construct a pipe from an [`OwnedFd`] representing
an anonymous pipe or a special FIFO file. The conversion assumes nothing about
the underlying pipe; it is left up to the user to make sure that the file
descriptor represents the reading end of a pipe and the pipe is set in
non-blocking mode.

### tokio::from_owned_fd_unchecked (function) › Panics

This function panics if it is not called from within a runtime with
IO enabled.

The runtime is usually set implicitly when this function is called
from a future driven by a tokio runtime, otherwise runtime can be set
explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.

## tokio::from_owned_fd_unchecked (function)

Creates a new `Sender` from an [`OwnedFd`] without checking pipe properties.

This function is intended to construct a pipe from an [`OwnedFd`] representing
an anonymous pipe or a special FIFO file. The conversion assumes nothing about
the underlying pipe; it is left up to the user to make sure that the file
descriptor represents the writing end of a pipe and the pipe is set in
non-blocking mode.

### tokio::from_owned_fd_unchecked (function) › Panics

This function panics if it is not called from within a runtime with
IO enabled.

The runtime is usually set implicitly when this function is called
from a future driven by a tokio runtime, otherwise runtime can be set
explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.

## tokio::from_raw (function)

Allows for listening to any valid OS signal.

For example, this can be used for listening for platform-specific
signals.
```rust,no_run
# use tokio::signal::unix::SignalKind;
# let signum = -1;
// let signum = libc::OS_SPECIFIC_SIGNAL;
let kind = SignalKind::from_raw(signum);
```

## tokio::from_raw_fd (function)

Converts a `RawFd` to a `TcpSocket`.

### tokio::from_raw_fd (function) › Notes

The caller is responsible for ensuring that the socket is in
non-blocking mode.

## tokio::from_raw_handle (function)

Constructs a new named pipe client from the specified raw handle.

This function will consume ownership of the handle given, passing
responsibility for closing the handle to the returned object.

This function is also unsafe as the primitives currently returned have
the contract that they are the sole owner of the file descriptor they
are wrapping. Usage of this function could accidentally allow violating
this contract which can cause memory unsafety in code that relies on it
being true.

### tokio::from_raw_handle (function) › Errors

This errors if called outside of a [Tokio Runtime], or in a runtime that
has not [enabled I/O], or if any OS-specific I/O errors occur.

[Tokio Runtime]: crate::runtime::Runtime
[enabled I/O]: crate::runtime::Builder::enable_io

## tokio::from_raw_handle (function)

Constructs a new named pipe server from the specified raw handle.

This function will consume ownership of the handle given, passing
responsibility for closing the handle to the returned object.

This function is also unsafe as the primitives currently returned have
the contract that they are the sole owner of the file descriptor they
are wrapping. Usage of this function could accidentally allow violating
this contract which can cause memory unsafety in code that relies on it
being true.

### tokio::from_raw_handle (function) › Errors

This errors if called outside of a [Tokio Runtime], or in a runtime that
has not [enabled I/O], or if any OS-specific I/O errors occur.

[Tokio Runtime]: crate::runtime::Runtime
[enabled I/O]: crate::runtime::Builder::enable_io

## tokio::from_raw_handle (function)

See [`std::os::windows::io::FromRawHandle::from_raw_handle`](https://doc.rust-lang.org/std/os/windows/io/trait.FromRawHandle.html#tymethod.from_raw_handle)

## tokio::from_raw_socket (function)

Converts a `RawSocket` to a `TcpStream`.

### tokio::from_raw_socket (function) › Notes

The caller is responsible for ensuring that the socket is in
non-blocking mode.

## tokio::from_raw_socket (function)

See [`std::os::windows::io::FromRawSocket::from_raw_socket`](https://doc.rust-lang.org/std/os/windows/io/trait.FromRawSocket.html#tymethod.from_raw_socket)

## tokio::from_std (function)

Converts a [`std::fs::File`] to a [`tokio::fs::File`](File).

### tokio::from_std (function) › Examples

```no_run
// This line could block. It is not recommended to do this on the Tokio
// runtime.
let std_file = std::fs::File::open("foo.txt").unwrap();
let file = tokio::fs::File::from_std(std_file);
```

## tokio::from_std (function)

Create a `tokio::time::Instant` from a `std::time::Instant`.

## tokio::from_std (function)

Creates an asynchronous `ChildStderr` from a synchronous one.

### tokio::from_std (function) › Errors

This method may fail if an error is encountered when setting the pipe to
non-blocking mode, or when registering the pipe with the runtime's IO
driver.

## tokio::from_std (function)

Creates an asynchronous `ChildStdin` from a synchronous one.

### tokio::from_std (function) › Errors

This method may fail if an error is encountered when setting the pipe to
non-blocking mode, or when registering the pipe with the runtime's IO
driver.

## tokio::from_std (function)

Creates an asynchronous `ChildStdout` from a synchronous one.

### tokio::from_std (function) › Errors

This method may fail if an error is encountered when setting the pipe to
non-blocking mode, or when registering the pipe with the runtime's IO
driver.

## tokio::from_std (function)

Creates new [`UnixListener`] from a [`std::os::unix::net::UnixListener`].

This function is intended to be used to wrap a `UnixListener` from the
standard library in the Tokio equivalent.

### tokio::from_std (function) › Notes

The caller is responsible for ensuring that the listener is in
non-blocking mode. Otherwise all I/O operations on the listener
will block the thread, which will cause unexpected behavior.
Non-blocking mode can be set using [`set_nonblocking`].

Passing a listener in blocking mode is always erroneous,
and the behavior in that case may change in the future.
For example, it could panic.

[`set_nonblocking`]: std::os::unix::net::UnixListener::set_nonblocking

### tokio::from_std (function) › Examples

```no_run
use tokio::net::UnixListener;
use std::os::unix::net::UnixListener as StdUnixListener;
# use std::error::Error;

# async fn dox() -> Result<(), Box<dyn Error>> {
let std_listener = StdUnixListener::bind("/path/to/the/socket")?;
std_listener.set_nonblocking(true)?;
let listener = UnixListener::from_std(std_listener)?;
# Ok(())
# }
```

### tokio::from_std (function) › Panics

This function panics if it is not called from within a runtime with
IO enabled.

The runtime is usually set implicitly when this function is called
from a future driven by a tokio runtime, otherwise runtime can be set
explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.

## tokio::from_std (function)

Creates new [`UnixStream`] from a [`std::os::unix::net::UnixStream`].

This function is intended to be used to wrap a `UnixStream` from the
standard library in the Tokio equivalent.

### tokio::from_std (function) › Notes

The caller is responsible for ensuring that the stream is in
non-blocking mode. Otherwise all I/O operations on the stream
will block the thread, which will cause unexpected behavior.
Non-blocking mode can be set using [`set_nonblocking`].

Passing a listener in blocking mode is always erroneous,
and the behavior in that case may change in the future.
For example, it could panic.

[`set_nonblocking`]: std::os::unix::net::UnixStream::set_nonblocking

### tokio::from_std (function) › Examples

```no_run
use tokio::net::UnixStream;
use std::os::unix::net::UnixStream as StdUnixStream;
# use std::error::Error;

# async fn dox() -> Result<(), Box<dyn Error>> {
let std_stream = StdUnixStream::connect("/path/to/the/socket")?;
std_stream.set_nonblocking(true)?;
let stream = UnixStream::from_std(std_stream)?;
# Ok(())
# }
```

### tokio::from_std (function) › Panics

This function panics if it is not called from within a runtime with
IO enabled.

The runtime is usually set implicitly when this function is called
from a future driven by a tokio runtime, otherwise runtime can be set
explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.

## tokio::from_std (function)

Creates new `TcpListener` from a `std::net::TcpListener`.

This function is intended to be used to wrap a TCP listener from the
standard library in the Tokio equivalent.

This API is typically paired with the `socket2` crate and the `Socket`
type to build up and customize a listener before it's shipped off to the
backing event loop. This allows configuration of options like
`SO_REUSEPORT`, binding to multiple addresses, etc.

### tokio::from_std (function) › Notes

The caller is responsible for ensuring that the listener is in
non-blocking mode. Otherwise all I/O operations on the listener
will block the thread, which will cause unexpected behavior.
Non-blocking mode can be set using [`set_nonblocking`].

Passing a listener in blocking mode is always erroneous,
and the behavior in that case may change in the future.
For example, it could panic.

[`set_nonblocking`]: std::net::TcpListener::set_nonblocking

### tokio::from_std (function) › Examples

```rust,no_run
use std::error::Error;
use tokio::net::TcpListener;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let std_listener = std::net::TcpListener::bind("127.0.0.1:0")?;
    std_listener.set_nonblocking(true)?;
    let listener = TcpListener::from_std(std_listener)?;
    Ok(())
}
```

### tokio::from_std (function) › Panics

This function panics if it is not called from within a runtime with
IO enabled.

The runtime is usually set implicitly when this function is called
from a future driven by a tokio runtime, otherwise runtime can be set
explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.

## tokio::from_std (function)

Creates new `TcpStream` from a `std::net::TcpStream`.

This function is intended to be used to wrap a TCP stream from the
standard library in the Tokio equivalent.

### tokio::from_std (function) › Notes

The caller is responsible for ensuring that the stream is in
non-blocking mode. Otherwise all I/O operations on the stream
will block the thread, which will cause unexpected behavior.
Non-blocking mode can be set using [`set_nonblocking`].

Passing a listener in blocking mode is always erroneous,
and the behavior in that case may change in the future.
For example, it could panic.

[`set_nonblocking`]: std::net::TcpStream::set_nonblocking

### tokio::from_std (function) › Examples

```rust,no_run
use std::error::Error;
use tokio::net::TcpStream;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let std_stream = std::net::TcpStream::connect("127.0.0.1:34254")?;
    std_stream.set_nonblocking(true)?;
    let stream = TcpStream::from_std(std_stream)?;
    Ok(())
}
```

### tokio::from_std (function) › Panics

This function panics if it is not called from within a runtime with
IO enabled.

The runtime is usually set implicitly when this function is called
from a future driven by a tokio runtime, otherwise runtime can be set
explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.

## tokio::from_std (function)

Creates new `UdpSocket` from a previously bound `std::net::UdpSocket`.

This function is intended to be used to wrap a UDP socket from the
standard library in the Tokio equivalent.

This can be used in conjunction with `socket2`'s `Socket` interface to
configure a socket before it's handed off, such as setting options like
`reuse_address` or binding to multiple addresses.

### tokio::from_std (function) › Notes

The caller is responsible for ensuring that the socket is in
non-blocking mode. Otherwise all I/O operations on the socket
will block the thread, which will cause unexpected behavior.
Non-blocking mode can be set using [`set_nonblocking`].

Passing a listener in blocking mode is always erroneous,
and the behavior in that case may change in the future.
For example, it could panic.

[`set_nonblocking`]: std::net::UdpSocket::set_nonblocking

### tokio::from_std (function) › Panics

This function panics if thread-local runtime is not set.

The runtime is usually set implicitly when this function is called
from a future driven by a tokio runtime, otherwise runtime can be set
explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.

### tokio::from_std (function) › Example

```no_run
use tokio::net::UdpSocket;
# use std::{io, net::SocketAddr};

# #[tokio::main]
# async fn main() -> io::Result<()> {
let addr = "0.0.0.0:8080".parse::<SocketAddr>().unwrap();
let std_sock = std::net::UdpSocket::bind(addr)?;
std_sock.set_nonblocking(true)?;
let sock = UdpSocket::from_std(std_sock)?;
// use `sock`
# Ok(())
# }
```

## tokio::from_std_stream (function)

Converts a [`std::net::TcpStream`] into a `TcpSocket`. The provided
socket must not have been connected prior to calling this function. This
function is typically used together with crates such as [`socket2`] to
configure socket options that are not available on `TcpSocket`.

[`std::net::TcpStream`]: struct@std::net::TcpStream
[`socket2`]: https://docs.rs/socket2/

### tokio::from_std_stream (function) › Notes

The caller is responsible for ensuring that the socket is in
non-blocking mode. Otherwise all I/O operations on the socket
will block the thread, which will cause unexpected behavior.
Non-blocking mode can be set using [`set_nonblocking`].

[`set_nonblocking`]: std::net::TcpStream::set_nonblocking

### tokio::from_std_stream (function) › Examples

```
use tokio::net::TcpSocket;
use socket2::{Domain, Socket, Type};

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let socket2_socket = Socket::new(Domain::IPV4, Type::STREAM, None)?;
    socket2_socket.set_nonblocking(true)?;

    let socket = TcpSocket::from_std_stream(socket2_socket.into());

    Ok(())
}
```

## tokio::fs::canonicalize::canonicalize (function)

Returns the canonical, absolute form of a path with all intermediate
components normalized and symbolic links resolved.

This is an async version of [`std::fs::canonicalize`].

### tokio::fs::canonicalize::canonicalize (function) › Platform-specific behavior

This function currently corresponds to the `realpath` function on Unix
and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
Note that, this [may change in the future][changes].

On Windows, this converts the path to use [extended length path][path]
syntax, which allows your program to use longer path names, but means you
can only join backslash-delimited paths to it, and it may be incompatible
with other applications (if passed to the application on the command-line,
or written to a file another application may read).

[changes]: https://doc.rust-lang.org/std/io/index.html#platform-specific-behavior
[path]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#maxpath

### tokio::fs::canonicalize::canonicalize (function) › Errors

This function will return an error in the following situations, but is not
limited to just these cases:

* `path` does not exist.
* A non-final component in path is not a directory.

### tokio::fs::canonicalize::canonicalize (function) › Examples

```no_run
use tokio::fs;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let path = fs::canonicalize("../a/../foo.txt").await?;
    Ok(())
}
```

## tokio::fs::copy::copy (function)

Copies the contents of one file to another. This function will also copy the permission bits
of the original file to the destination file.
This function will overwrite the contents of to.

This is the async equivalent of [`std::fs::copy`].

### tokio::fs::copy::copy (function) › Examples

```no_run
use tokio::fs;

# async fn dox() -> std::io::Result<()> {
fs::copy("foo.txt", "bar.txt").await?;
# Ok(())
# }
```

## tokio::fs::create_dir::create_dir (function)

Creates a new, empty directory at the provided path.

This is an async version of [`std::fs::create_dir`].

### tokio::fs::create_dir::create_dir (function) › Platform-specific behavior

This function currently corresponds to the `mkdir` function on Unix
and the `CreateDirectory` function on Windows.
Note that, this [may change in the future][changes].

[changes]: https://doc.rust-lang.org/std/io/index.html#platform-specific-behavior

**NOTE**: If a parent of the given path doesn't exist, this function will
return an error. To create a directory and all its missing parents at the
same time, use the [`create_dir_all`] function.

### tokio::fs::create_dir::create_dir (function) › Errors

This function will return an error in the following situations, but is not
limited to just these cases:

* User lacks permissions to create directory at `path`.
* A parent of the given path doesn't exist. (To create a directory and all
  its missing parents at the same time, use the [`create_dir_all`]
  function.)
* `path` already exists.

[`create_dir_all`]: super::create_dir_all()

### tokio::fs::create_dir::create_dir (function) › Examples

```no_run
use tokio::fs;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    fs::create_dir("/some/dir").await?;
    Ok(())
}
```

## tokio::fs::create_dir_all::create_dir_all (function)

Recursively creates a directory and all of its parent components if they
are missing.

This is an async version of [`std::fs::create_dir_all`].

### tokio::fs::create_dir_all::create_dir_all (function) › Platform-specific behavior

This function currently corresponds to the `mkdir` function on Unix
and the `CreateDirectory` function on Windows.
Note that, this [may change in the future][changes].

[changes]: https://doc.rust-lang.org/std/io/index.html#platform-specific-behavior

### tokio::fs::create_dir_all::create_dir_all (function) › Errors

This function will return an error in the following situations, but is not
limited to just these cases:

* If any directory in the path specified by `path` does not already exist
  and it could not be created otherwise. The specific error conditions for
  when a directory is being created (after it is determined to not exist) are
  outlined by [`fs::create_dir`].

If the final component at `path` already exists and is a directory, this
function will also return successfully without error.

Notable exception is made for situations where any of the directories
specified in the `path` could not be created as it was being created concurrently.
Such cases are considered to be successful. That is, calling `create_dir_all`
concurrently from multiple threads or processes is guaranteed not to fail
due to a race condition with itself.

[`fs::create_dir`]: std::fs::create_dir

### tokio::fs::create_dir_all::create_dir_all (function) › Examples

```no_run
use tokio::fs;

#[tokio::main]
async fn main() -> std::io::Result<()> {
    fs::create_dir_all("/some/dir").await?;
    Ok(())
}
```

## tokio::fs::dir_builder::DirBuilder (struct)

A builder for creating directories in various manners.

This is a specialized version of [`std::fs::DirBuilder`] for usage on
the Tokio runtime.

## tokio::fs::file::File (struct)

A reference to an open file on the filesystem.

This is a specialized version of [`std::fs::File`] for usage from the
Tokio runtime.

An instance of a `File` can be read and/or written depending on what options
it was opened with. Files also implement [`AsyncSeek`] to alter the logical
cursor that the file contains internally.

A file will not be closed immediately when it goes out of scope if there
are any IO operations that have not yet completed. To ensure that a file is
closed immediately when it is dropped, you should call [`flush`] before
dropping it. Note that this does not ensure that the file has been fully
written to disk; the operating system might keep the changes around in an
in-memory buffer. See the [`sync_all`] method for telling the OS to write
the data to disk.

Reading and writing to a `File` is usually done using the convenience
methods found on the [`AsyncReadExt`] and [`AsyncWriteExt`] traits.

[`AsyncSeek`]: trait@crate::io::AsyncSeek
[`flush`]: fn@crate::io::AsyncWriteExt::flush
[`sync_all`]: fn@crate::fs::File::sync_all
[`AsyncReadExt`]: trait@crate::io::AsyncReadExt
[`AsyncWriteExt`]: trait@crate::io::AsyncWriteExt

### tokio::fs::file::File (struct) › Examples

Create a new file and asynchronously write bytes to it:

```no_run
use tokio::fs::File;
use tokio::io::AsyncWriteExt; // for write_all()

# async fn dox() -> std::io::Result<()> {
let mut file = File::create("foo.txt").await?;
file.write_all(b"hello, world!").await?;
# Ok(())
# }
```

Read the contents of a file into a buffer:

```no_run
use tokio::fs::File;
use tokio::io::AsyncReadExt; // for read_to_end()

# async fn dox() -> std::io::Result<()> {
let mut file = File::open("foo.txt").await?;

let mut contents = vec![];
file.read_to_end(&mut contents).await?;

println!("len = {}", contents.len());
# Ok(())
# }
```

## tokio::fs::hard_link::hard_link (function)

Creates a new hard link on the filesystem.

This is an async version of [`std::fs::hard_link`].

The `link` path will be a link pointing to the `original` path. Note that systems
often require these two paths to both be located on the same filesystem.

### tokio::fs::hard_link::hard_link (function) › Platform-specific behavior

This function currently corresponds to the `link` function on Unix
and the `CreateHardLink` function on Windows.
Note that, this [may change in the future][changes].

[changes]: https://doc.rust-lang.org/std/io/index.html#platform-specific-behavior

### tokio::fs::hard_link::hard_link (function) › Errors

This function will return an error in the following situations, but is not
limited to just these cases:

* The `original` path is not a file or doesn't exist.

### tokio::fs::hard_link::hard_link (function) › Examples

```no_run
use tokio::fs;

#[tokio::main]
async fn main() -> std::io::Result<()> {
    fs::hard_link("a.txt", "b.txt").await?; // Hard link a.txt to b.txt
    Ok(())
}
```

## tokio::fs::metadata::metadata (function)

Given a path, queries the file system to get information about a file,
directory, etc.

This is an async version of [`std::fs::metadata`].

This function will traverse symbolic links to query information about the
destination file.

### tokio::fs::metadata::metadata (function) › Platform-specific behavior

This function currently corresponds to the `stat` function on Unix and the
`GetFileAttributesEx` function on Windows.  Note that, this [may change in
the future][changes].

[changes]: https://doc.rust-lang.org/std/io/index.html#platform-specific-behavior

### tokio::fs::metadata::metadata (function) › Errors

This function will return an error in the following situations, but is not
limited to just these cases:

* The user lacks permissions to perform `metadata` call on `path`.
* `path` does not exist.

### tokio::fs::metadata::metadata (function) › Examples

```rust,no_run
use tokio::fs;

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let attr = fs::metadata("/some/file/path.txt").await?;
    // inspect attr ...
    Ok(())
}
```

## tokio::fs::open_options::OpenOptions (struct)

Options and flags which can be used to configure how a file is opened.

This builder exposes the ability to configure how a [`File`] is opened and
what operations are permitted on the open file. The [`File::open`] and
[`File::create`] methods are aliases for commonly used options using this
builder.

Generally speaking, when using `OpenOptions`, you'll first call [`new`],
then chain calls to methods to set each option, then call [`open`], passing
the path of the file you're trying to open. This will give you a
[`io::Result`] with a [`File`] inside that you can further operate
on.

This is a specialized version of [`std::fs::OpenOptions`] for usage from
the Tokio runtime.

`From<std::fs::OpenOptions>` is implemented for more advanced configuration
than the methods provided here.

[`new`]: OpenOptions::new
[`open`]: OpenOptions::open
[`File`]: File
[`File::open`]: File::open
[`File::create`]: File::create

### tokio::fs::open_options::OpenOptions (struct) › Examples

Opening a file to read:

```no_run
use tokio::fs::OpenOptions;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let file = OpenOptions::new()
        .read(true)
        .open("foo.txt")
        .await?;

    Ok(())
}
```

Opening a file for both reading and writing, as well as creating it if it
doesn't exist:

```no_run
use tokio::fs::OpenOptions;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let file = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .open("foo.txt")
        .await?;

    Ok(())
}
```

## tokio::fs::read::read (function)

Reads the entire contents of a file into a bytes vector.

This is an async version of [`std::fs::read`].

This is a convenience function for using [`File::open`] and [`read_to_end`]
with fewer imports and without an intermediate variable. It pre-allocates a
buffer based on the file size when available, so it is generally faster than
reading into a vector created with `Vec::new()`.

This operation is implemented by running the equivalent blocking operation
on a separate thread pool using [`spawn_blocking`].

[`File::open`]: super::File::open
[`read_to_end`]: crate::io::AsyncReadExt::read_to_end
[`spawn_blocking`]: crate::task::spawn_blocking

### tokio::fs::read::read (function) › Errors

This function will return an error if `path` does not already exist.
Other errors may also be returned according to [`OpenOptions::open`].

[`OpenOptions::open`]: super::OpenOptions::open

It will also return an error if it encounters while reading an error
of a kind other than [`ErrorKind::Interrupted`].

[`ErrorKind::Interrupted`]: std::io::ErrorKind::Interrupted

### tokio::fs::read::read (function) › io_uring support

On Linux, you can also use io_uring for executing system calls. To enable
io_uring, you need to specify the `--cfg tokio_unstable` flag at compile time,
enable the io-uring cargo feature, and set the `Builder::enable_io_uring`
runtime option.

Support for io_uring is currently experimental, so its behavior may change
or it may be removed in future versions.

### tokio::fs::read::read (function) › Examples

```no_run
use tokio::fs;
use std::net::SocketAddr;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
    let contents = fs::read("address.txt").await?;
    let foo: SocketAddr = String::from_utf8_lossy(&contents).parse()?;
    Ok(())
}
```

## tokio::fs::read_dir::DirEntry (struct)

Entries returned by the [`ReadDir`] stream.

[`ReadDir`]: struct@ReadDir

This is a specialized version of [`std::fs::DirEntry`] for usage from the
Tokio runtime.

An instance of `DirEntry` represents an entry inside of a directory on the
filesystem. Each entry can be inspected via methods to learn about the full
path or possibly other metadata through per-platform extension traits.

## tokio::fs::read_dir::ReadDir (struct)

Reads the entries in a directory.

This struct is returned from the [`read_dir`] function of this module and
will yield instances of [`DirEntry`]. Through a [`DirEntry`] information
like the entry's path and possibly other metadata can be learned.

A `ReadDir` can be turned into a `Stream` with [`ReadDirStream`].

[`ReadDirStream`]: https://docs.rs/tokio-stream/0.1/tokio_stream/wrappers/struct.ReadDirStream.html

### tokio::fs::read_dir::ReadDir (struct) › Errors

This stream will return an [`Err`] if there's some sort of intermittent
IO error during iteration.

[`read_dir`]: read_dir
[`DirEntry`]: DirEntry
[`Err`]: std::result::Result::Err

## tokio::fs::read_dir::read_dir (function)

Returns a stream over the entries within a directory.

This is an async version of [`std::fs::read_dir`].

This operation is implemented by running the equivalent blocking
operation on a separate thread pool using [`spawn_blocking`].

[`spawn_blocking`]: crate::task::spawn_blocking

## tokio::fs::read_link::read_link (function)

Reads a symbolic link, returning the file that the link points to.

This is an async version of [`std::fs::read_link`].

## tokio::fs::read_to_string::read_to_string (function)

Creates a future which will open a file for reading and read the entire
contents into a string and return said string.

This is the async equivalent of [`std::fs::read_to_string`][std].

This operation is implemented by running the equivalent blocking operation
on a separate thread pool using [`spawn_blocking`].

[`spawn_blocking`]: crate::task::spawn_blocking
[std]: fn@std::fs::read_to_string

### tokio::fs::read_to_string::read_to_string (function) › Examples

```no_run
use tokio::fs;

# async fn dox() -> std::io::Result<()> {
let contents = fs::read_to_string("foo.txt").await?;
println!("foo.txt contains {} bytes", contents.len());
# Ok(())
# }
```

## tokio::fs::remove_dir::remove_dir (function)

Removes an existing, empty directory.

This is an async version of [`std::fs::remove_dir`].

## tokio::fs::remove_dir_all::remove_dir_all (function)

Removes a directory at this path, after removing all its contents. Use carefully!

This is an async version of [`std::fs::remove_dir_all`][std]

[std]: fn@std::fs::remove_dir_all

## tokio::fs::remove_file::remove_file (function)

Removes a file from the filesystem.

Note that there is no guarantee that the file is immediately deleted (e.g.
depending on platform, other open file descriptors may prevent immediate
removal).

This is an async version of [`std::fs::remove_file`].

## tokio::fs::rename::rename (function)

Renames a file or directory to a new name, replacing the original file if
`to` already exists.

This will not work if the new name is on a different mount point.

This is an async version of [`std::fs::rename`].

## tokio::fs::set_permissions::set_permissions (function)

Changes the permissions found on a file or a directory.

This is an async version of [`std::fs::set_permissions`][std]

[std]: fn@std::fs::set_permissions

## tokio::fs::symlink::symlink (function)

Creates a new symbolic link on the filesystem.

The `link` path will be a symbolic link pointing to the `original` path.

This is an async version of [`std::os::unix::fs::symlink`].

## tokio::fs::symlink_dir::symlink_dir (function)

Creates a new directory symlink on the filesystem.

The `link` path will be a directory symbolic link pointing to the `original`
path.

This is an async version of [`std::os::windows::fs::symlink_dir`][std]

[std]: https://doc.rust-lang.org/std/os/windows/fs/fn.symlink_dir.html

## tokio::fs::symlink_file::symlink_file (function)

Creates a new file symbolic link on the filesystem.

The `link` path will be a file symbolic link pointing to the `original`
path.

This is an async version of [`std::os::windows::fs::symlink_file`][std]

[std]: https://doc.rust-lang.org/std/os/windows/fs/fn.symlink_file.html

## tokio::fs::symlink_metadata::symlink_metadata (function)

Queries the file system metadata for a path.

This is an async version of [`std::fs::symlink_metadata`][std]

[std]: fn@std::fs::symlink_metadata

## tokio::fs::try_exists::try_exists (function)

Returns `Ok(true)` if the path points at an existing entity.

This function will traverse symbolic links to query information about the
destination file. In case of broken symbolic links this will return `Ok(false)`.

This is the async equivalent of [`std::path::Path::try_exists`][std].

[std]: fn@std::path::Path::try_exists

### tokio::fs::try_exists::try_exists (function) › Examples

```no_run
use tokio::fs;

# async fn dox() -> std::io::Result<()> {
fs::try_exists("foo.txt").await?;
# Ok(())
# }
```

## tokio::fs::write::write (function)

Creates a future that will open a file for writing and write the entire
contents of `contents` to it.

This is the async equivalent of [`std::fs::write`][std].

This operation is implemented by running the equivalent blocking operation
on a separate thread pool using [`spawn_blocking`].

[`spawn_blocking`]: crate::task::spawn_blocking
[std]: fn@std::fs::write

### tokio::fs::write::write (function) › Examples

```no_run
use tokio::fs;

# async fn dox() -> std::io::Result<()> {
fs::write("foo.txt", b"Hello world!").await?;
# Ok(())
# }
```

## tokio::future::maybe_done::MaybeDone (enum)

A future that may have completed.

## tokio::future::maybe_done::MaybeDone::Done (variant)

The output of the completed future.

## tokio::future::maybe_done::MaybeDone::Future (variant)

A not-yet-completed future.

## tokio::future::maybe_done::MaybeDone::Gone (variant)

The empty variant after the result of a [`MaybeDone`] has been
taken using the [`take_output`](MaybeDone::take_output) method.

## tokio::future::maybe_done::maybe_done (function)

Wraps a future into a `MaybeDone`.

## tokio::get (function)

Returns a copy of the task-local value
if the task-local value implements `Clone`.

### tokio::get (function) › Panics

This function will panic if the task local doesn't have a value set.

## tokio::get (function)

Returns a reference to the value currently stored in the `OnceCell`, or
`None` if the `OnceCell` is empty.

## tokio::get (function)

Returns a reference to the value currently stored in the `SetOnce`, or
`None` if the `SetOnce` is empty.

## tokio::get_inner (function)

Returns a shared reference to the backing object of the inner [`AsyncFd`].

## tokio::get_inner (function)

Returns a shared reference to the backing object of the inner [`AsyncFd`].

## tokio::get_inner_mut (function)

Returns a mutable reference to the backing object of the inner [`AsyncFd`].

## tokio::get_kill_on_drop (function)

Returns the boolean value that was previously set by [`Command::kill_on_drop`].

Note that if you have not previously called [`Command::kill_on_drop`], the
default value of `false` will be returned here.

### tokio::get_kill_on_drop (function) › Examples

```
use tokio::process::Command;

let mut cmd = Command::new("echo");
assert!(!cmd.get_kill_on_drop());

cmd.kill_on_drop(true);
assert!(cmd.get_kill_on_drop());
```

## tokio::get_mut (function)

Gets a mutable reference to the underlying I/O object.

It is inadvisable to directly read from the underlying I/O object.

## tokio::get_mut (function)

Gets a mutable reference to the underlying reader.

Care should be taken to avoid modifying the internal I/O state of the
underlying reader as doing so may corrupt the internal limit of this
`Take`.

## tokio::get_mut (function)

Gets a mutable reference to the underlying reader.

It is inadvisable to directly read from the underlying reader.

## tokio::get_mut (function)

Gets a mutable reference to the underlying value in this timeout.

## tokio::get_mut (function)

Gets a mutable reference to the underlying writer.

It is inadvisable to directly write to the underlying writer.

## tokio::get_mut (function)

Gets mutable references to the underlying readers in this `Chain`.

Care should be taken to avoid modifying the internal I/O state of the
underlying readers as doing so may corrupt the internal state of this
`Chain`.

## tokio::get_mut (function)

Obtains a mutable reference to the underlying reader.

## tokio::get_mut (function)

Returns a mutable reference to the backing object of this [`AsyncFd`].

## tokio::get_mut (function)

Returns a mutable reference to the inner [`AsyncFd`].

## tokio::get_mut (function)

Returns a mutable reference to the underlying data.

Since this call borrows the `Mutex` mutably, no actual locking needs to
take place -- the mutable borrow statically guarantees no locks exist.

### tokio::get_mut (function) › Examples

```
use tokio::sync::Mutex;

fn main() {
    let mut mutex = Mutex::new(1);

    let n = mutex.get_mut();
    *n = 2;
}
```

## tokio::get_mut (function)

Returns a mutable reference to the underlying data.

Since this call borrows the `RwLock` mutably, no actual locking needs to
take place -- the mutable borrow statically guarantees no locks exist.

### tokio::get_mut (function) › Examples

```
use tokio::sync::RwLock;

fn main() {
    let mut lock = RwLock::new(1);

    let n = lock.get_mut();
    *n = 2;
}
```

## tokio::get_mut (function)

Returns a mutable reference to the value currently stored in the
`OnceCell`, or `None` if the `OnceCell` is empty.

Since this call borrows the `OnceCell` mutably, it is safe to mutate the
value inside the `OnceCell` — the mutable borrow statically guarantees
no other references exist.

## tokio::get_or_init (function)

Gets the value currently in the `OnceCell`, or initialize it with the
given asynchronous operation.

If some other task is currently working on initializing the `OnceCell`,
this call will wait for that other task to finish, then return the value
that the other task produced.

If the provided operation is cancelled or panics, the initialization
attempt is cancelled. If there are other tasks waiting for the value to
be initialized, one of them will start another attempt at initializing
the value.

This will deadlock if `f` tries to initialize the cell recursively.

## tokio::get_or_try_init (function)

Gets the value currently in the `OnceCell`, or initialize it with the
given asynchronous operation.

If some other task is currently working on initializing the `OnceCell`,
this call will wait for that other task to finish, then return the value
that the other task produced.

If the provided operation returns an error, is cancelled or panics, the
initialization attempt is cancelled. If there are other tasks waiting
for the value to be initialized, one of them will start another attempt
at initializing the value.

This will deadlock if `f` tries to initialize the cell recursively.

## tokio::get_pin_mut (function)

Gets a pinned mutable reference to the underlying I/O object.

It is inadvisable to directly read from the underlying I/O object.

## tokio::get_pin_mut (function)

Gets a pinned mutable reference to the underlying reader.

Care should be taken to avoid modifying the internal I/O state of the
underlying reader as doing so may corrupt the internal limit of this
`Take`.

## tokio::get_pin_mut (function)

Gets a pinned mutable reference to the underlying reader.

It is inadvisable to directly read from the underlying reader.

## tokio::get_pin_mut (function)

Gets a pinned mutable reference to the underlying writer.

It is inadvisable to directly write to the underlying writer.

## tokio::get_pin_mut (function)

Gets pinned mutable references to the underlying readers in this `Chain`.

Care should be taken to avoid modifying the internal I/O state of the
underlying readers as doing so may corrupt the internal state of this
`Chain`.

## tokio::get_ref (function)

Gets a reference to the underlying I/O object.

It is inadvisable to directly read from the underlying I/O object.

## tokio::get_ref (function)

Gets a reference to the underlying reader.

## tokio::get_ref (function)

Gets a reference to the underlying reader.

It is inadvisable to directly read from the underlying reader.

## tokio::get_ref (function)

Gets a reference to the underlying value in this timeout.

## tokio::get_ref (function)

Gets a reference to the underlying writer.

## tokio::get_ref (function)

Gets references to the underlying readers in this `Chain`.

## tokio::get_ref (function)

Obtains a reference to the underlying reader.

## tokio::get_ref (function)

Returns a shared reference to the backing object of this [`AsyncFd`].

## tokio::get_ref (function)

Returns a shared reference to the inner [`AsyncFd`].

## tokio::get_ref (function)

Returns a shared reference to the inner [`AsyncFd`].

## tokio::gid (function)

Gets GID (group ID) of the process.

## tokio::gid (function)

Similar to `uid` but sets the group ID of the child process. This has
the same semantics as the `uid` field.

## tokio::global_queue_depth (function)

Returns the number of tasks currently scheduled in the runtime's
global queue.

Tasks that are spawned or notified from a non-runtime thread are
scheduled using the runtime's global queue. This metric returns the
**current** number of tasks pending in the global queue. As such, the
returned value may increase or decrease as new tasks are scheduled and
processed.

### tokio::global_queue_depth (function) › Examples

```
use tokio::runtime::Handle;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let metrics = Handle::current().metrics();

let n = metrics.global_queue_depth();
println!("{} tasks currently pending in the runtime's global queue", n);
# }
```

## tokio::global_queue_interval (function)

Sets the number of scheduler ticks after which the scheduler will poll the global
task queue.

A scheduler "tick" roughly corresponds to one `poll` invocation on a task.

By default the global queue interval is 31 for the current-thread scheduler. Please see
[the module documentation] for the default behavior of the multi-thread scheduler.

Schedulers have a local queue of already-claimed tasks, and a global queue of incoming
tasks. Setting the interval to a smaller value increases the fairness of the scheduler,
at the cost of more synchronization overhead. That can be beneficial for prioritizing
getting started on new work, especially if tasks frequently yield rather than complete
or await on further I/O. Setting the interval to `1` will prioritize the global queue and
tasks from the local queue will be executed only if the global queue is empty.
Conversely, a higher value prioritizes existing work, and is a good choice when most
tasks quickly complete polling.

[the module documentation]: crate::runtime#multi-threaded-runtime-behavior-at-the-time-of-writing

### tokio::global_queue_interval (function) › Panics

This function will panic if 0 is passed as an argument.

### tokio::global_queue_interval (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
# use tokio::runtime;
# pub fn main() {
let rt = runtime::Builder::new_multi_thread()
    .global_queue_interval(31)
    .build();
# }
# }
```

## tokio::handle (function)

Returns a handle to the runtime's spawner.

The returned handle can be used to spawn tasks that run on this runtime, and can
be cloned to allow moving the `Handle` to other threads.

As the handle can be sent to other threads, it can only be used to spawn tasks that are `Send`.

Calling [`Handle::block_on`] on a handle to a `LocalRuntime` is error-prone.
Refer to the documentation of [`Handle::block_on`] for more.

### tokio::handle (function) › Examples

```
use tokio::runtime::LocalRuntime;

let rt = LocalRuntime::new()
    .unwrap();

let handle = rt.handle();

// Use the handle...
```

## tokio::handle (function)

Returns a handle to the runtime's spawner.

The returned handle can be used to spawn tasks that run on this runtime, and can
be cloned to allow moving the `Handle` to other threads.

Calling [`Handle::block_on`] on a handle to a `current_thread` runtime is error-prone.
Refer to the documentation of [`Handle::block_on`] for more.

### tokio::handle (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime::Runtime;

let rt = Runtime::new()
    .unwrap();

let handle = rt.handle();

// Use the handle...
# }
```

## tokio::hangup (function)

Represents the `SIGHUP` signal.

On Unix systems this signal is sent when the terminal is disconnected.
By default, the process is terminated by this signal.

## tokio::has_changed (function)

Checks if this channel contains a message that this receiver has not yet
seen. The current value will not be marked as seen.

Although this method is called `has_changed`, it does not check
messages for equality, so this call will return true even if the current
message is equal to the previous message.

### tokio::has_changed (function) › Errors

Returns a [`RecvError`](error::RecvError) if and only if the channel has been closed.

### tokio::has_changed (function) › Examples

### tokio::has_changed (function) › Basic usage

```
use tokio::sync::watch;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = watch::channel("hello");

tx.send("goodbye").unwrap();

assert!(rx.has_changed().unwrap());
assert_eq!(*rx.borrow_and_update(), "goodbye");

// The value has been marked as seen
assert!(!rx.has_changed().unwrap());
# }
```

### tokio::has_changed (function) › Closed channel example

```
use tokio::sync::watch;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, rx) = watch::channel("hello");
tx.send("goodbye").unwrap();

drop(tx);

// The channel is closed
assert!(rx.has_changed().is_err());
# }
```

## tokio::has_changed (function)

Indicates if the borrowed value is considered as _changed_ since the last
time it has been marked as seen.

Unlike [`Receiver::has_changed()`], this method does not fail if the channel is closed.

When borrowed from the [`Sender`] this function will always return `false`.

### tokio::has_changed (function) › Examples

```
use tokio::sync::watch;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = watch::channel("hello");

tx.send("goodbye").unwrap();
// The sender does never consider the value as changed.
assert!(!tx.borrow().has_changed());

// Drop the sender immediately, just for testing purposes.
drop(tx);

// Even if the sender has already been dropped...
assert!(rx.has_changed().is_err());
// ...the modified value is still readable and detected as changed.
assert_eq!(*rx.borrow(), "goodbye");
assert!(rx.borrow().has_changed());

// Read the changed value and mark it as seen.
{
    let received = rx.borrow_and_update();
    assert_eq!(*received, "goodbye");
    assert!(received.has_changed());
    // Release the read lock when leaving this scope.
}

// Now the value has already been marked as seen and could
// never be modified again (after the sender has been dropped).
assert!(!rx.borrow().has_changed());
# }
```

## tokio::id (function)

Return the opaque ID of the task.

## tokio::id (function)

Returns a [task ID] that identifies the task which errored relative to
other currently spawned tasks.

[task ID]: crate::task::Id

## tokio::id (function)

Returns a [task ID] that uniquely identifies this task relative to other
currently spawned tasks.

[task ID]: crate::task::Id

## tokio::id (function)

Returns a [task ID] that uniquely identifies this task relative to other
currently spawned tasks.

[task ID]: crate::task::Id

## tokio::id (function)

Returns a [task ID] that uniquely identifies this task relative to other
tasks spawned at the time of the dump.

**Note**: This is an [unstable API][unstable]. The public API of this type
may break in 1.x releases. See [the documentation on unstable
features][unstable] for details.

[task ID]: crate::task::Id
[unstable]: crate#unstable-features

## tokio::id (function)

Returns the OS-assigned process identifier associated with this child
while it is still running.

Once the child has been polled to completion this will return `None`.
This is done to avoid confusion on platforms like Unix where the OS
identifier could be reused once the process has completed.

## tokio::id (function)

Returns the [`Id`] of the current [`LocalSet`] runtime.

### tokio::id (function) › Examples

```rust
use tokio::task;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let local_set = task::LocalSet::new();
println!("Local set id: {}", local_set.id());
# }
```

[`Id`]: struct@crate::runtime::Id

## tokio::id (function)

Returns the [`Id`] of the current `Runtime`.

### tokio::id (function) › Examples

```
use tokio::runtime::Handle;

#[tokio::main(flavor = "current_thread")]
async fn main() {
  println!("Current runtime id: {}", Handle::current().id());
}
```

[`Id`]: struct@crate::runtime::Id

## tokio::in_buffer_size (function)

The number of bytes to reserve for the input buffer.

This corresponds to specifying [`nInBufferSize`].

[`nInBufferSize`]: https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createnamedpipea

## tokio::in_buffer_size (struct_field)

The number of bytes to reserve for the input buffer.

## tokio::info (function)

Retrieves information about the named pipe the client is associated
with.

```no_run
use tokio::net::windows::named_pipe::{ClientOptions, PipeEnd, PipeMode};

const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-client-info";

# #[tokio::main] async fn main() -> std::io::Result<()> {
let client = ClientOptions::new()
    .open(PIPE_NAME)?;

let client_info = client.info()?;

assert_eq!(client_info.end, PipeEnd::Client);
assert_eq!(client_info.mode, PipeMode::Message);
assert_eq!(client_info.max_instances, 5);
# Ok(()) }
```

## tokio::info (function)

Retrieves information about the named pipe the server is associated
with.

```no_run
use tokio::net::windows::named_pipe::{PipeEnd, PipeMode, ServerOptions};

const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-server-info";

# #[tokio::main] async fn main() -> std::io::Result<()> {
let server = ServerOptions::new()
    .pipe_mode(PipeMode::Message)
    .max_instances(5)
    .create(PIPE_NAME)?;

let server_info = server.info()?;

assert_eq!(server_info.end, PipeEnd::Server);
assert_eq!(server_info.mode, PipeMode::Message);
assert_eq!(server_info.max_instances, 5);
# Ok(()) }
```

## tokio::initialize_unfilled (function)

Returns a mutable reference to the unfilled part of the buffer, ensuring it is fully initialized.

Since `ReadBuf` tracks the region of the buffer that has been initialized, this is effectively "free" after
the first use.

## tokio::initialize_unfilled_to (function)

Returns a mutable reference to the first `n` bytes of the unfilled part of the buffer, ensuring it is
fully initialized.

### tokio::initialize_unfilled_to (function) › Panics

Panics if `self.remaining()` is less than `n`.

## tokio::initialized (function)

Returns `true` if the `OnceCell` currently contains a value, and `false`
otherwise.

## tokio::initialized (function)

Returns `true` if the `SetOnce` currently contains a value, and `false`
otherwise.

## tokio::initialized (function)

Returns a shared reference to the initialized portion of the buffer.

This includes the filled portion.

## tokio::initialized_mut (function)

Returns a mutable reference to the initialized portion of the buffer.

This includes the filled portion.

## tokio::inner_mut (function)

Returns a mutable reference to the entire buffer, without ensuring that it has been fully
initialized.

The elements between 0 and `self.filled().len()` are filled, and those between 0 and
`self.initialized().len()` are initialized (and so can be converted to a `&mut [u8]`).

The caller of this method must ensure that these invariants are upheld. For example, if the
caller initializes some of the uninitialized section of the buffer, it must call
[`assume_init`](Self::assume_init) with the number of bytes initialized.

### tokio::inner_mut (function) › Safety

The caller must not de-initialize portions of the buffer that have already been initialized.
This includes any bytes in the region marked as uninitialized by `ReadBuf`.

## tokio::ino (function)

Returns the underlying `d_ino` field in the contained `dirent`
structure.

### tokio::ino (function) › Examples

```
use tokio::fs;

# #[tokio::main]
# async fn main() -> std::io::Result<()> {
let mut entries = fs::read_dir(".").await?;
while let Some(entry) = entries.next_entry().await? {
    // Here, `entry` is a `DirEntry`.
    println!("{:?}: {}", entry.file_name(), entry.ino());
}
# Ok(())
# }
```

## tokio::interrupt (function)

Represents the `SIGINT` signal.

On Unix systems this signal is sent to interrupt a program.
By default, the process is terminated by this signal.

## tokio::into_blocking_fd (function)

Converts the pipe into an [`OwnedFd`] in blocking mode.

This function will deregister this pipe end from the event loop, set
it in blocking mode and perform the conversion.

## tokio::into_blocking_fd (function)

Converts the pipe into an [`OwnedFd`] in blocking mode.

This function will deregister this pipe end from the event loop, set
it in blocking mode and perform the conversion.

## tokio::into_inner (function)

Consume the `SendTimeoutError`, returning the unsent value.

## tokio::into_inner (function)

Consume the `TrySendError`, returning the unsent value.

## tokio::into_inner (function)

Consumes the `Chain`, returning the wrapped readers.

## tokio::into_inner (function)

Consumes the `Take`, returning the wrapped reader.

## tokio::into_inner (function)

Consumes the lock, returning the underlying data.

## tokio::into_inner (function)

Consumes the mutex, returning the underlying data.
### tokio::into_inner (function) › Examples

```
use tokio::sync::Mutex;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let mutex = Mutex::new(1);

let n = mutex.into_inner();
assert_eq!(n, 1);
# }
```

## tokio::into_inner (function)

Consumes this `BufReader`, returning the underlying reader.

Note that any leftover data in the internal buffer is lost.

## tokio::into_inner (function)

Consumes this `BufStream`, returning the underlying I/O object.

Note that any leftover data in the internal buffer is lost.

## tokio::into_inner (function)

Consumes this `BufWriter`, returning the underlying writer.

Note that any leftover data in the internal buffer is lost.

## tokio::into_inner (function)

Consumes this timeout, returning the underlying value.

## tokio::into_inner (function)

Deregisters this file descriptor and returns ownership of the backing
object.

## tokio::into_inner (function)

Destroy the [`Aio`] and return its inner source.

## tokio::into_inner (function)

Splits this `Join` back into its `AsyncRead` and `AsyncWrite`
components.

## tokio::into_inner (function)

Takes the value from the cell, destroying the cell in the process.
Returns `None` if the cell is empty.

## tokio::into_inner (function)

Takes the value from the cell, destroying the cell in the process.
Returns `None` if the cell is empty.

## tokio::into_inner (function)

Unwraps this `Lines<R>`, returning the underlying reader.

Note that any leftover data in the internal buffer is lost.
Therefore, a following read from the underlying reader may lead to data loss.

## tokio::into_mapped (function)

Converts this `OwnedRwLockWriteGuard` into an
`OwnedRwLockMappedWriteGuard`. This method can be used to store a
non-mapped guard in a struct field that expects a mapped guard.

This is equivalent to calling `OwnedRwLockWriteGuard::map(guard, |me| me)`.

## tokio::into_mapped (function)

Converts this `RwLockWriteGuard` into an `RwLockMappedWriteGuard`. This
method can be used to store a non-mapped guard in a struct field that
expects a mapped guard.

This is equivalent to calling `RwLockWriteGuard::map(guard, |me| me)`.

## tokio::into_nonblocking_fd (function)

Converts the pipe into an [`OwnedFd`] in nonblocking mode.

This function will deregister this pipe end from the event loop and
perform the conversion. Returned file descriptor will be in nonblocking
mode.

## tokio::into_nonblocking_fd (function)

Converts the pipe into an [`OwnedFd`] in nonblocking mode.

This function will deregister this pipe end from the event loop and
perform the conversion. The returned file descriptor will be in nonblocking
mode.

## tokio::into_owned_fd (function)

Convert into [`OwnedFd`].

## tokio::into_owned_fd (function)

Convert into [`OwnedFd`].

## tokio::into_owned_fd (function)

Convert into [`OwnedFd`].

## tokio::into_owned_handle (function)

Convert into [`OwnedHandle`].

## tokio::into_owned_handle (function)

Convert into [`OwnedHandle`].

## tokio::into_owned_handle (function)

Convert into [`OwnedHandle`].

## tokio::into_panic (function)

Consumes the join error, returning the object with which the task panicked.

### tokio::into_panic (function) › Panics

`into_panic()` panics if the `Error` does not represent the underlying
task terminating with a panic. Use `is_panic` to check the error reason
or `try_into_panic` for a variant that does not panic.

### tokio::into_panic (function) › Examples

```should_panic,ignore-wasm
use std::panic;

#[tokio::main]
async fn main() {
    let err = tokio::spawn(async {
        panic!("boom");
    }).await.unwrap_err();

    if err.is_panic() {
        // Resume the panic on the main task
        panic::resume_unwind(err.into_panic());
    }
}
```

## tokio::into_parts (function)

Returns the original object passed to [`try_new`] or [`try_with_interest`]
alongside the error that caused these functions to fail.

[`try_new`]: AsyncFd::try_new
[`try_with_interest`]: AsyncFd::try_with_interest

## tokio::into_raw_socket (function)

See [`std::os::windows::io::IntoRawSocket::into_raw_socket`](https://doc.rust-lang.org/std/os/windows/io/trait.IntoRawSocket.html#tymethod.into_raw_socket)

## tokio::into_split (function)

Splits a `TcpStream` into a read half and a write half, which can be used
to read and write the stream concurrently.

Unlike [`split`], the owned halves can be moved to separate tasks, however
this comes at the cost of a heap allocation.

**Note:** Dropping the write half will shut down the write half of the TCP
stream. This is equivalent to calling [`shutdown()`] on the `TcpStream`.

[`split`]: TcpStream::split()
[`shutdown()`]: fn@crate::io::AsyncWriteExt::shutdown

## tokio::into_split (function)

Splits a `UnixStream` into a read half and a write half, which can be used
to read and write the stream concurrently.

Unlike [`split`], the owned halves can be moved to separate tasks, however
this comes at the cost of a heap allocation.

**Note:** Dropping the write half will only shut down the write half of the
stream. This is equivalent to calling [`shutdown()`] on the `UnixStream`.

[`split`]: Self::split()
[`shutdown()`]: fn@crate::io::AsyncWriteExt::shutdown

## tokio::into_std (function)

Cheaply convert into a `std::process::Command`.

Note that Tokio specific options will be lost. Currently, this only applies to [`kill_on_drop`].

[`kill_on_drop`]: Command::kill_on_drop

## tokio::into_std (function)

Convert the value into a `std::time::Instant`.

## tokio::into_std (function)

Destructures `File` into a [`std::fs::File`]. This function is
async to allow any in-flight operations to complete.

Use `File::try_into_std` to attempt conversion immediately.

### tokio::into_std (function) › Examples

```no_run
use tokio::fs::File;

# async fn dox() -> std::io::Result<()> {
let tokio_file = File::open("foo.txt").await?;
let std_file = tokio_file.into_std().await;
# Ok(())
# }
```

## tokio::into_std (function)

Turns a [`tokio::net::TcpListener`] into a [`std::net::TcpListener`].

The returned [`std::net::TcpListener`] will have nonblocking mode set as
`true`.  Use [`set_nonblocking`] to change the blocking mode if needed.

### tokio::into_std (function) › Examples

```rust,no_run
use std::error::Error;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let tokio_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
    let std_listener = tokio_listener.into_std()?;
    std_listener.set_nonblocking(false)?;
    Ok(())
}
```

[`tokio::net::TcpListener`]: TcpListener
[`std::net::TcpListener`]: std::net::TcpListener
[`set_nonblocking`]: fn@std::net::TcpListener::set_nonblocking

## tokio::into_std (function)

Turns a [`tokio::net::TcpStream`] into a [`std::net::TcpStream`].

The returned [`std::net::TcpStream`] will have nonblocking mode set as `true`.
Use [`set_nonblocking`] to change the blocking mode if needed.

### tokio::into_std (function) › Examples

```
use std::error::Error;
use std::io::Read;
use tokio::net::TcpListener;
# use tokio::net::TcpStream;
# use tokio::io::AsyncWriteExt;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let mut data = [0u8; 12];
#   if false {
    let listener = TcpListener::bind("127.0.0.1:34254").await?;
#   }
#   let listener = TcpListener::bind("127.0.0.1:0").await?;
#   let addr = listener.local_addr().unwrap();
#   let handle = tokio::spawn(async move {
#       let mut stream: TcpStream = TcpStream::connect(addr).await.unwrap();
#       stream.write_all(b"Hello world!").await.unwrap();
#   });
    let (tokio_tcp_stream, _) = listener.accept().await?;
    let mut std_tcp_stream = tokio_tcp_stream.into_std()?;
#   handle.await.expect("The task being joined has panicked");
    std_tcp_stream.set_nonblocking(false)?;
    std_tcp_stream.read_exact(&mut data)?;
#   assert_eq!(b"Hello world!", &data);
    Ok(())
}
```
[`tokio::net::TcpStream`]: TcpStream
[`std::net::TcpStream`]: std::net::TcpStream
[`set_nonblocking`]: fn@std::net::TcpStream::set_nonblocking

## tokio::into_std (function)

Turns a [`tokio::net::UdpSocket`] into a [`std::net::UdpSocket`].

The returned [`std::net::UdpSocket`] will have nonblocking mode set as
`true`.  Use [`set_nonblocking`] to change the blocking mode if needed.

### tokio::into_std (function) › Examples

```rust,no_run
use std::error::Error;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let tokio_socket = tokio::net::UdpSocket::bind("127.0.0.1:0").await?;
    let std_socket = tokio_socket.into_std()?;
    std_socket.set_nonblocking(false)?;
    Ok(())
}
```

[`tokio::net::UdpSocket`]: UdpSocket
[`std::net::UdpSocket`]: std::net::UdpSocket
[`set_nonblocking`]: fn@std::net::UdpSocket::set_nonblocking

## tokio::into_std (function)

Turns a [`tokio::net::UnixListener`] into a [`std::os::unix::net::UnixListener`].

The returned [`std::os::unix::net::UnixListener`] will have nonblocking mode
set as `true`. Use [`set_nonblocking`] to change the blocking mode if needed.

### tokio::into_std (function) › Examples

```rust,no_run
# use std::error::Error;
# async fn dox() -> Result<(), Box<dyn Error>> {
let tokio_listener = tokio::net::UnixListener::bind("/path/to/the/socket")?;
let std_listener = tokio_listener.into_std()?;
std_listener.set_nonblocking(false)?;
# Ok(())
# }
```

[`tokio::net::UnixListener`]: UnixListener
[`std::os::unix::net::UnixListener`]: std::os::unix::net::UnixListener
[`set_nonblocking`]: fn@std::os::unix::net::UnixListener::set_nonblocking

## tokio::into_std (function)

Turns a [`tokio::net::UnixStream`] into a [`std::os::unix::net::UnixStream`].

The returned [`std::os::unix::net::UnixStream`] will have nonblocking
mode set as `true`.  Use [`set_nonblocking`] to change the blocking
mode if needed.

### tokio::into_std (function) › Examples

```
use std::error::Error;
use std::io::Read;
use tokio::net::UnixListener;
# use tokio::net::UnixStream;
# use tokio::io::AsyncWriteExt;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
#   if cfg!(miri) { return Ok(()); } // No Unix domain sockets in miri.
    let dir = tempfile::tempdir().unwrap();
    let bind_path = dir.path().join("bind_path");

    let mut data = [0u8; 12];
    let listener = UnixListener::bind(&bind_path)?;
#   let handle = tokio::spawn(async {
#       let mut stream = UnixStream::connect(bind_path).await.unwrap();
#       stream.write(b"Hello world!").await.unwrap();
#   });
    let (tokio_unix_stream, _) = listener.accept().await?;
    let mut std_unix_stream = tokio_unix_stream.into_std()?;
#   handle.await.expect("The task being joined has panicked");
    std_unix_stream.set_nonblocking(false)?;
    std_unix_stream.read_exact(&mut data)?;
#   assert_eq!(b"Hello world!", &data);
    Ok(())
}
```
[`tokio::net::UnixStream`]: UnixStream
[`std::os::unix::net::UnixStream`]: std::os::unix::net::UnixStream
[`set_nonblocking`]: fn@std::os::unix::net::UnixStream::set_nonblocking

## tokio::invalid (function)

Creates an error representing a misconfigured timer.

## tokio::io (function)

Represents the `SIGIO` signal.

On Unix systems this signal is sent when I/O operations are possible
on some file descriptor. By default, this signal is ignored.

## tokio::io::async_buf_read::AsyncBufRead (trait)

Reads bytes asynchronously.

This trait is analogous to [`std::io::BufRead`], but integrates with
the asynchronous task system. In particular, the [`poll_fill_buf`] method,
unlike [`BufRead::fill_buf`], will automatically queue the current task for wakeup
and return if data is not yet available, rather than blocking the calling
thread.

Utilities for working with `AsyncBufRead` values are provided by
[`AsyncBufReadExt`].

[`std::io::BufRead`]: std::io::BufRead
[`poll_fill_buf`]: AsyncBufRead::poll_fill_buf
[`BufRead::fill_buf`]: std::io::BufRead::fill_buf
[`AsyncBufReadExt`]: crate::io::AsyncBufReadExt

## tokio::io::async_fd::AsyncFd (struct)

Associates an IO object backed by a Unix file descriptor with the tokio
reactor, allowing for readiness to be polled. The file descriptor must be of
a type that can be used with the OS polling facilities (ie, `poll`, `epoll`,
`kqueue`, etc), such as a network socket or pipe, and the file descriptor
must have the nonblocking mode set to true.

Creating an [`AsyncFd`] registers the file descriptor with the current tokio
Reactor, allowing you to directly await the file descriptor being readable
or writable. Once registered, the file descriptor remains registered until
the [`AsyncFd`] is dropped.

The [`AsyncFd`] takes ownership of an arbitrary object to represent the IO
object. It is intended that the inner object will handle closing the file
descriptor when it is dropped, avoiding resource leaks and ensuring that the
[`AsyncFd`] can clean up the registration before closing the file descriptor.
The [`AsyncFd::into_inner`] function can be used to extract the inner object
to retake control from the tokio IO reactor. The [`OwnedFd`] type is often
used as the inner object, as it is the simplest type that closes the fd on
drop.

The inner object is required to implement [`AsRawFd`]. This file descriptor
must not change while [`AsyncFd`] owns the inner object, i.e. the
[`AsRawFd::as_raw_fd`] method on the inner type must always return the same
file descriptor when called multiple times. Failure to uphold this results
in unspecified behavior in the IO driver, which may include breaking
notifications for other sockets/etc.

Polling for readiness is done by calling the async functions [`readable`]
and [`writable`]. These functions complete when the associated readiness
condition is observed. Any number of tasks can query the same `AsyncFd` in
parallel, on the same or different conditions.

On some platforms, the readiness detecting mechanism relies on
edge-triggered notifications. This means that the OS will only notify Tokio
when the file descriptor transitions from not-ready to ready. For this to
work you should first try to read or write and only poll for readiness
if that fails with an error of [`std::io::ErrorKind::WouldBlock`].

Tokio internally tracks when it has received a ready notification, and when
readiness checking functions like [`readable`] and [`writable`] are called,
if the readiness flag is set, these async functions will complete
immediately. This however does mean that it is critical to ensure that this
ready flag is cleared when (and only when) the file descriptor ceases to be
ready. The [`AsyncFdReadyGuard`] returned from readiness checking functions
serves this function; after calling a readiness-checking async function,
you must use this [`AsyncFdReadyGuard`] to signal to tokio whether the file
descriptor is no longer in a ready state.

### tokio::io::async_fd::AsyncFd (struct) › Use with to a poll-based API

In some cases it may be desirable to use `AsyncFd` from APIs similar to
[`TcpStream::poll_read_ready`]. The [`AsyncFd::poll_read_ready`] and
[`AsyncFd::poll_write_ready`] functions are provided for this purpose.
Because these functions don't create a future to hold their state, they have
the limitation that only one task can wait on each direction (read or write)
at a time.

### tokio::io::async_fd::AsyncFd (struct) › Examples

This example shows how to turn [`std::net::TcpStream`] asynchronous using
`AsyncFd`.  It implements the read/write operations both as an `async fn`
and using the IO traits [`AsyncRead`] and [`AsyncWrite`].

```no_run
use std::io::{self, Read, Write};
use std::net::TcpStream;
use std::pin::Pin;
use std::task::{ready, Context, Poll};
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use tokio::io::unix::AsyncFd;

pub struct AsyncTcpStream {
    inner: AsyncFd<TcpStream>,
}

impl AsyncTcpStream {
    pub fn new(tcp: TcpStream) -> io::Result<Self> {
        tcp.set_nonblocking(true)?;
        Ok(Self {
            inner: AsyncFd::new(tcp)?,
        })
    }

    pub async fn read(&self, out: &mut [u8]) -> io::Result<usize> {
        loop {
            let mut guard = self.inner.readable().await?;

            match guard.try_io(|inner| inner.get_ref().read(out)) {
                Ok(result) => return result,
                Err(_would_block) => continue,
            }
        }
    }

    pub async fn write(&self, buf: &[u8]) -> io::Result<usize> {
        loop {
            let mut guard = self.inner.writable().await?;

            match guard.try_io(|inner| inner.get_ref().write(buf)) {
                Ok(result) => return result,
                Err(_would_block) => continue,
            }
        }
    }
}

impl AsyncRead for AsyncTcpStream {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>
    ) -> Poll<io::Result<()>> {
        loop {
            let mut guard = ready!(self.inner.poll_read_ready(cx))?;

            let unfilled = buf.initialize_unfilled();
            match guard.try_io(|inner| inner.get_ref().read(unfilled)) {
                Ok(Ok(len)) => {
                    buf.advance(len);
                    return Poll::Ready(Ok(()));
                },
                Ok(Err(err)) => return Poll::Ready(Err(err)),
                Err(_would_block) => continue,
            }
        }
    }
}

impl AsyncWrite for AsyncTcpStream {
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8]
    ) -> Poll<io::Result<usize>> {
        loop {
            let mut guard = ready!(self.inner.poll_write_ready(cx))?;

            match guard.try_io(|inner| inner.get_ref().write(buf)) {
                Ok(result) => return Poll::Ready(result),
                Err(_would_block) => continue,
            }
        }
    }

    fn poll_flush(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<io::Result<()>> {
        // tcp flush is a no-op
        Poll::Ready(Ok(()))
    }

    fn poll_shutdown(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<io::Result<()>> {
        self.inner.get_ref().shutdown(std::net::Shutdown::Write)?;
        Poll::Ready(Ok(()))
    }
}
```

[`readable`]: method@Self::readable
[`writable`]: method@Self::writable
[`AsyncFdReadyGuard`]: struct@self::AsyncFdReadyGuard
[`TcpStream::poll_read_ready`]: struct@crate::net::TcpStream
[`AsyncRead`]: trait@crate::io::AsyncRead
[`AsyncWrite`]: trait@crate::io::AsyncWrite
[`OwnedFd`]: struct@std::os::fd::OwnedFd

## tokio::io::async_fd::AsyncFdReadyGuard (struct)

Represents an IO-ready event detected on a particular file descriptor that
has not yet been acknowledged. This is a `must_use` structure to help ensure
that you do not forget to explicitly clear (or not clear) the event.

This type exposes an immutable reference to the underlying IO object.

## tokio::io::async_fd::AsyncFdReadyMutGuard (struct)

Represents an IO-ready event detected on a particular file descriptor that
has not yet been acknowledged. This is a `must_use` structure to help ensure
that you do not forget to explicitly clear (or not clear) the event.

This type exposes a mutable reference to the underlying IO object.

## tokio::io::async_fd::AsyncFdTryNewError (struct)

Error returned by [`try_new`] or [`try_with_interest`].

[`try_new`]: AsyncFd::try_new
[`try_with_interest`]: AsyncFd::try_with_interest

## tokio::io::async_fd::TryIoError (struct)

The error type returned by [`try_io`].

This error indicates that the IO resource returned a [`WouldBlock`] error.

[`WouldBlock`]: std::io::ErrorKind::WouldBlock
[`try_io`]: method@AsyncFdReadyGuard::try_io

## tokio::io::async_read::AsyncRead (trait)

Reads bytes from a source.

This trait is analogous to the [`std::io::Read`] trait, but integrates with
the asynchronous task system. In particular, the [`poll_read`] method,
unlike [`Read::read`], will automatically queue the current task for wakeup
and return if data is not yet available, rather than blocking the calling
thread.

Specifically, this means that the `poll_read` function will return one of
the following:

* `Poll::Ready(Ok(()))` means that data was immediately read and placed into
  the output buffer. The amount of data read can be determined by the
  increase in the length of the slice returned by `ReadBuf::filled`. If the
  difference is 0, either EOF has been reached, or the output buffer had zero
  capacity (i.e. `buf.remaining()` == 0).

* `Poll::Pending` means that no data was read into the buffer
  provided. The I/O object is not currently readable but may become readable
  in the future. Most importantly, **the current future's task is scheduled
  to get unparked when the object is readable**. This means that like
  `Future::poll` you'll receive a notification when the I/O object is
  readable again.

* `Poll::Ready(Err(e))` for other errors are standard I/O errors coming from the
  underlying object.

This trait importantly means that the `read` method only works in the
context of a future's task. The object may panic if used outside of a task.

Utilities for working with `AsyncRead` values are provided by
[`AsyncReadExt`].

[`poll_read`]: AsyncRead::poll_read
[`std::io::Read`]: std::io::Read
[`Read::read`]: std::io::Read::read
[`AsyncReadExt`]: crate::io::AsyncReadExt

## tokio::io::async_seek::AsyncSeek (trait)

Seek bytes asynchronously.

This trait is analogous to the [`std::io::Seek`] trait, but integrates
with the asynchronous task system. In particular, the `start_seek`
method, unlike [`Seek::seek`], will not block the calling thread.

Utilities for working with `AsyncSeek` values are provided by
[`AsyncSeekExt`].

[`std::io::Seek`]: std::io::Seek
[`Seek::seek`]: std::io::Seek::seek()
[`AsyncSeekExt`]: crate::io::AsyncSeekExt

## tokio::io::async_write::AsyncWrite (trait)

Writes bytes asynchronously.

This trait is analogous to the [`std::io::Write`] trait, but integrates with
the asynchronous task system. In particular, the [`poll_write`] method,
unlike [`Write::write`], will automatically queue the current task for wakeup
and return if data is not yet available, rather than blocking the calling
thread.

Specifically, this means that the [`poll_write`] function will return one of
the following:

* `Poll::Ready(Ok(n))` means that `n` bytes of data was immediately
  written.

* `Poll::Pending` means that no data was written from the buffer
  provided. The I/O object is not currently writable but may become writable
  in the future. Most importantly, **the current future's task is scheduled
  to get unparked when the object is writable**. This means that like
  `Future::poll` you'll receive a notification when the I/O object is
  writable again.

* `Poll::Ready(Err(e))` for other errors are standard I/O errors coming from the
  underlying object.

Utilities for working with `AsyncWrite` values are provided by
[`AsyncWriteExt`]. Most users will interact with `AsyncWrite` types through
these extension methods, which provide ergonomic async functions such as
`write_all` and `flush`.

[`std::io::Write`]: std::io::Write
[`Write::write`]: std::io::Write::write()
[`poll_write`]: AsyncWrite::poll_write()
[`AsyncWriteExt`]: crate::io::AsyncWriteExt

## tokio::io::bsd::poll_aio::Aio (struct)

Associates a POSIX AIO control block with the reactor that drives it.

`Aio`'s wrapped type must implement [`AioSource`] to be driven
by the reactor.

The wrapped source may be accessed through the `Aio` via the `Deref` and
`DerefMut` traits.

### tokio::io::bsd::poll_aio::Aio (struct) › Clearing readiness

If [`Aio::poll_ready`] returns ready, but the consumer determines that the
Source is not completely ready and must return to the Pending state,
[`Aio::clear_ready`] may be used.  This can be useful with
[`lio_listio`], which may generate a kevent when only a portion of the
operations have completed.

### tokio::io::bsd::poll_aio::Aio (struct) › Platforms

Only FreeBSD implements POSIX AIO with kqueue notification, so
`Aio` is only available for that operating system.

[`lio_listio`]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/lio_listio.html

## tokio::io::bsd::poll_aio::AioEvent (struct)

Opaque data returned by [`Aio::poll_ready`].

It can be fed back to [`Aio::clear_ready`].

## tokio::io::bsd::poll_aio::AioSource (trait)

Like [`mio::event::Source`], but for POSIX AIO only.

Tokio's consumer must pass an implementer of this trait to create a
[`Aio`] object.  Implementers must implement at least one of [`AioSource::register`] and
[`AioSource::register_borrowed`].

## tokio::io::interest::Interest (struct)

Readiness event interest.

Specifies the readiness events the caller is interested in when awaiting on
I/O resource readiness states.

## tokio::io::join::Join (struct)

Joins two values implementing `AsyncRead` and `AsyncWrite` into a
single handle.

## tokio::io::join::join (function)

Join two values implementing `AsyncRead` and `AsyncWrite` into a
single handle.

## tokio::io::read_buf::ReadBuf (struct)

A wrapper around a byte buffer that is incrementally filled and initialized.

This type is a sort of "double cursor". It tracks three regions in the
buffer: a region at the beginning of the buffer that has been logically
filled with data, a region that has been initialized at some point but not
yet logically filled, and a region at the end that may be uninitialized.
The filled region is guaranteed to be a subset of the initialized region.

In summary, the contents of the buffer can be visualized as:

```not_rust
[             capacity              ]
[ filled |         unfilled         ]
[    initialized    | uninitialized ]
```

It is undefined behavior to de-initialize any bytes from the uninitialized
region, since it is merely unknown whether this region is uninitialized or
not, and if part of it turns out to be initialized, it must stay initialized.

## tokio::io::ready::Ready (struct)

Describes the readiness state of an I/O resources.

`Ready` tracks which operation an I/O resource is ready to perform.

## tokio::io::seek::Seek (struct)

Future for the [`seek`](crate::io::AsyncSeekExt::seek) method.

## tokio::io::split::ReadHalf (struct)

The readable half of a value returned from [`split`](split()).

## tokio::io::split::WriteHalf (struct)

The writable half of a value returned from [`split`](split()).

## tokio::io::split::split (function)

Splits a single value implementing `AsyncRead + AsyncWrite` into separate
`AsyncRead` and `AsyncWrite` handles.

To restore this read/write object from its `ReadHalf` and
`WriteHalf` use [`unsplit`](ReadHalf::unsplit()).

## tokio::io::stderr::Stderr (struct)

A handle to the standard error stream of a process.

Concurrent writes to stderr must be executed with care: Only individual
writes to this [`AsyncWrite`] are guaranteed to be intact. In particular
you should be aware that writes using [`write_all`] are not guaranteed
to occur as a single write, so multiple threads writing data with
[`write_all`] may result in interleaved output.

Created by the [`stderr`] function.

[`stderr`]: stderr()
[`AsyncWrite`]: AsyncWrite
[`write_all`]: crate::io::AsyncWriteExt::write_all()

### tokio::io::stderr::Stderr (struct) › Examples

```
use tokio::io::{self, AsyncWriteExt};

#[tokio::main]
async fn main() -> io::Result<()> {
    let mut stderr = io::stderr();
    stderr.write_all(b"Print some error here.").await?;
    Ok(())
}
```

## tokio::io::stderr::stderr (function)

Constructs a new handle to the standard error of the current process.

The returned handle allows writing to standard error from the within the
Tokio runtime.

Concurrent writes to stderr must be executed with care: Only individual
writes to this [`AsyncWrite`] are guaranteed to be intact. In particular
you should be aware that writes using [`write_all`] are not guaranteed
to occur as a single write, so multiple threads writing data with
[`write_all`] may result in interleaved output.

Note that unlike [`std::io::stderr`], each call to this `stderr()`
produces a new writer, so for example, this program does **not** flush stderr:

```no_run
# use tokio::io::AsyncWriteExt;
# #[tokio::main]
# async fn main() -> std::io::Result<()> {
tokio::io::stderr().write_all(b"aa").await?;
tokio::io::stderr().flush().await?;
# Ok(())
# }
```

[`std::io::stderr`]: std::io::stderr
[`AsyncWrite`]: AsyncWrite
[`write_all`]: crate::io::AsyncWriteExt::write_all()

### tokio::io::stderr::stderr (function) › Examples

```
use tokio::io::{self, AsyncWriteExt};

#[tokio::main]
async fn main() -> io::Result<()> {
    let mut stderr = io::stderr();
    stderr.write_all(b"Print some error here.").await?;
    Ok(())
}
```

## tokio::io::stdin::Stdin (struct)

A handle to the standard input stream of a process.

The handle implements the [`AsyncRead`] trait, but beware that concurrent
reads of `Stdin` must be executed with care.

This handle is best used for non-interactive uses, such as when a file
is piped into the application. For technical reasons, `stdin` is
implemented by using an ordinary blocking read on a separate thread, and
it is impossible to cancel that read. This can make shutdown of the
runtime hang until the user presses enter.

For interactive uses, it is recommended to spawn a thread dedicated to
user input and use blocking IO directly in that thread.

Created by the [`stdin`] function.

[`stdin`]: fn@stdin
[`AsyncRead`]: trait@AsyncRead

## tokio::io::stdin::stdin (function)

Constructs a new handle to the standard input of the current process.

This handle is best used for non-interactive uses, such as when a file
is piped into the application. For technical reasons, `stdin` is
implemented by using an ordinary blocking read on a separate thread, and
it is impossible to cancel that read. This can make shutdown of the
runtime hang until the user presses enter.

For interactive uses, it is recommended to spawn a thread dedicated to
user input and use blocking IO directly in that thread.

## tokio::io::stdout::Stdout (struct)

A handle to the standard output stream of a process.

Concurrent writes to stdout must be executed with care: Only individual
writes to this [`AsyncWrite`] are guaranteed to be intact. In particular
you should be aware that writes using [`write_all`] are not guaranteed
to occur as a single write, so multiple threads writing data with
[`write_all`] may result in interleaved output.

### tokio::io::stdout::Stdout (struct) › Warning

Each call to [`stdout()`] creates a **new** handle with its own
internal state. Writes through different handles are not
coordinated, so creating a new handle in a loop can cause output
to appear out of order:

```no_run
# use tokio::io::{self, AsyncWriteExt};
# #[tokio::main]
# async fn main() -> std::io::Result<()> {
// WRONG: creates a new handle each iteration
for i in 0..10 {
    let mut out = io::stdout();
    out.write_all(b"data").await?;
    out.write_all(b"\n").await?;
    // out is dropped here; its last write may still be
    // running when the next iteration starts
}
# Ok(())
# }
```

To preserve order, create one handle outside the loop and
reuse it:

```no_run
# use tokio::io::{self, AsyncWriteExt};
# #[tokio::main]
# async fn main() -> std::io::Result<()> {
let mut out = io::stdout();
for i in 0..10 {
    out.write_all(b"data").await?;
    out.write_all(b"\n").await?;
}
# Ok(())
# }
```

Created by the [`stdout`] function.

[`stdout`]: stdout()
[`AsyncWrite`]: AsyncWrite
[`write_all`]: crate::io::AsyncWriteExt::write_all()

### tokio::io::stdout::Stdout (struct) › Examples

```
use tokio::io::{self, AsyncWriteExt};

#[tokio::main]
async fn main() -> io::Result<()> {
    let mut stdout = io::stdout();
    stdout.write_all(b"Hello world!").await?;
    Ok(())
}
```

The following is an example of using `stdio` with loop.

```
use tokio::io::{self, AsyncWriteExt};

#[tokio::main]
async fn main() {
    let messages = vec!["hello", " world\n"];

    // When you use `stdio` in a loop, it is recommended to create
    // a single `stdio` instance outside the loop and call a write
    // operation against that instance on each loop.
    //
    // Repeatedly creating `stdout` instances inside the loop and
    // writing to that handle could result in mangled output since
    // each write operation is handled by a different blocking thread.
    let mut stdout = io::stdout();

    for message in &messages {
        stdout.write_all(message.as_bytes()).await.unwrap();
        stdout.flush().await.unwrap();
    }
}
```

## tokio::io::stdout::stdout (function)

Constructs a new handle to the standard output of the current process.

The returned handle allows writing to standard out from the within the
Tokio runtime.

Concurrent writes to stdout must be executed with care: Only individual
writes to this [`AsyncWrite`] are guaranteed to be intact. In particular
you should be aware that writes using [`write_all`] are not guaranteed
to occur as a single write, so multiple threads writing data with
[`write_all`] may result in interleaved output.

Note that unlike [`std::io::stdout`], each call to this `stdout()`
produces a new writer, so for example, this program does **not** flush stdout:

```no_run
# use tokio::io::AsyncWriteExt;
# #[tokio::main]
# async fn main() -> std::io::Result<()> {
tokio::io::stdout().write_all(b"aa").await?;
tokio::io::stdout().flush().await?;
# Ok(())
# }
```

[`std::io::stdout`]: std::io::stdout
[`AsyncWrite`]: AsyncWrite
[`write_all`]: crate::io::AsyncWriteExt::write_all()

### tokio::io::stdout::stdout (function) › Examples

```
use tokio::io::{self, AsyncWriteExt};

#[tokio::main]
async fn main() -> io::Result<()> {
    let mut stdout = io::stdout();
    stdout.write_all(b"Hello world!").await?;
    Ok(())
}
```

The following is an example of using `stdio` with loop.

```
use tokio::io::{self, AsyncWriteExt};

#[tokio::main]
async fn main() {
    let messages = vec!["hello", " world\n"];

    // When you use `stdio` in a loop, it is recommended to create
    // a single `stdio` instance outside the loop and call a write
    // operation against that instance on each loop.
    //
    // Repeatedly creating `stdout` instances inside the loop and
    // writing to that handle could result in mangled output since
    // each write operation is handled by a different blocking thread.
    let mut stdout = io::stdout();

    for message in &messages {
        stdout.write_all(message.as_bytes()).await.unwrap();
        stdout.flush().await.unwrap();
    }
}
```

## tokio::io::util::async_buf_read_ext::AsyncBufReadExt (trait)

An extension trait which adds utility methods to [`AsyncBufRead`] types.

[`AsyncBufRead`]: crate::io::AsyncBufRead

## tokio::io::util::async_read_ext::AsyncReadExt (trait)

Reads bytes from a source.

Implemented as an extension trait, adding utility methods to all
[`AsyncRead`] types. Callers will tend to import this trait instead of
[`AsyncRead`].

```no_run
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::fs::File;
use tokio::io::{self, AsyncReadExt};

#[tokio::main]
async fn main() -> io::Result<()> {
    let mut f = File::open("foo.txt").await?;
    let mut buffer = [0; 10];

    // The `read` method is defined by this trait.
    let n = f.read(&mut buffer[..]).await?;

    Ok(())
}
# }
```

See [module][crate::io] documentation for more details.

[`AsyncRead`]: AsyncRead

## tokio::io::util::async_seek_ext::AsyncSeekExt (trait)

An extension trait that adds utility methods to [`AsyncSeek`] types.

### tokio::io::util::async_seek_ext::AsyncSeekExt (trait) › Examples

```
use std::io::{self, Cursor, SeekFrom};
use tokio::io::{AsyncSeekExt, AsyncReadExt};

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut cursor = Cursor::new(b"abcdefg");

// the `seek` method is defined by this trait
cursor.seek(SeekFrom::Start(3)).await?;

let mut buf = [0; 1];
let n = cursor.read(&mut buf).await?;
assert_eq!(n, 1);
assert_eq!(buf, [b'd']);

Ok(())
# }
```

See [module][crate::io] documentation for more details.

[`AsyncSeek`]: AsyncSeek

## tokio::io::util::async_write_ext::AsyncWriteExt (trait)

Writes bytes to a sink.

Implemented as an extension trait, adding utility methods to all
[`AsyncWrite`] types. Callers will tend to import this trait instead of
[`AsyncWrite`].

```no_run
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::io::{self, AsyncWriteExt};
use tokio::fs::File;

#[tokio::main]
async fn main() -> io::Result<()> {
    let data = b"some bytes";

    let mut pos = 0;
    let mut buffer = File::create("foo.txt").await?;

    while pos < data.len() {
        let bytes_written = buffer.write(&data[pos..]).await?;
        pos += bytes_written;
    }

    Ok(())
}
# }
```

See [module][crate::io] documentation for more details.

[`AsyncWrite`]: AsyncWrite

## tokio::io::util::buf_reader::BufReader (struct)

The `BufReader` struct adds buffering to any reader.

It can be excessively inefficient to work directly with a [`AsyncRead`]
instance. A `BufReader` performs large, infrequent reads on the underlying
[`AsyncRead`] and maintains an in-memory buffer of the results.

`BufReader` can improve the speed of programs that make *small* and
*repeated* read calls to the same file or network socket. It does not
help when reading very large amounts at once, or reading just one or a few
times. It also provides no advantage when reading from a source that is
already in memory, like a `Vec<u8>`.

When the `BufReader` is dropped, the contents of its buffer will be
discarded. Creating multiple instances of a `BufReader` on the same
stream can cause data loss.

## tokio::io::util::buf_stream::BufStream (struct)

Wraps a type that is [`AsyncWrite`] and [`AsyncRead`], and buffers its input and output.

It can be excessively inefficient to work directly with something that implements [`AsyncWrite`]
and [`AsyncRead`]. For example, every `write`, however small, has to traverse the syscall
interface, and similarly, every read has to do the same. The [`BufWriter`] and [`BufReader`]
types aid with these problems respectively, but do so in only one direction. `BufStream` wraps
one in the other so that both directions are buffered. See their documentation for details.

## tokio::io::util::buf_writer::BufWriter (struct)

Wraps a writer and buffers its output.

It can be excessively inefficient to work directly with something that
implements [`AsyncWrite`]. A `BufWriter` keeps an in-memory buffer of data and
writes it to an underlying writer in large, infrequent batches.

`BufWriter` can improve the speed of programs that make *small* and
*repeated* write calls to the same file or network socket. It does not
help when writing very large amounts at once, or writing just one or a few
times. It also provides no advantage when writing to a destination that is
in memory, like a `Vec<u8>`.

When the `BufWriter` is dropped, the contents of its buffer will be
discarded. Creating multiple instances of a `BufWriter` on the same
stream can cause data loss. If you need to write out the contents of its
buffer, you must manually call flush before the writer is dropped.

[`AsyncWrite`]: AsyncWrite
[`flush`]: super::AsyncWriteExt::flush

## tokio::io::util::chain::Chain (struct)

Stream for the [`chain`](super::AsyncReadExt::chain) method.

## tokio::io::util::copy::copy (function)

Asynchronously copies the entire contents of a reader into a writer.

This function returns a future that will continuously read data from
`reader` and then write it into `writer` in a streaming fashion until
`reader` returns EOF or fails.

On success, the total number of bytes that were copied from `reader` to
`writer` is returned.

This is an asynchronous version of [`std::io::copy`][std].

A heap-allocated copy buffer with 8 KB is created to take data from the
reader to the writer, check [`copy_buf`] if you want an alternative for
[`AsyncBufRead`]. You can use `copy_buf` with [`BufReader`] to change the
buffer capacity.

### tokio::io::util::copy::copy (function) › When to use async alternatives instead of `SyncIoBridge`

If you are looking to use [`std::io::copy`] with a synchronous consumer
(like a `hasher` or compressor), consider using async alternatives instead of
wrapping the reader with [`SyncIoBridge`].
See the [`SyncIoBridge`] documentation for detailed examples and guidance.

[std]: std::io::copy
[`copy_buf`]: crate::io::copy_buf
[`AsyncBufRead`]: crate::io::AsyncBufRead
[`BufReader`]: crate::io::BufReader
[`SyncIoBridge`]: https://docs.rs/tokio-util/latest/tokio_util/io/struct.SyncIoBridge.html

### tokio::io::util::copy::copy (function) › Errors

The returned future will return an error immediately if any call to
`poll_read` or `poll_write` returns an error.

### tokio::io::util::copy::copy (function) › Examples

```
use tokio::io;

# async fn dox() -> std::io::Result<()> {
let mut reader: &[u8] = b"hello";
let mut writer: Vec<u8> = vec![];

io::copy(&mut reader, &mut writer).await?;

assert_eq!(&b"hello"[..], &writer[..]);
# Ok(())
# }
```

## tokio::io::util::copy_bidirectional::copy_bidirectional (function)

Copies data in both directions between `a` and `b`.

This function returns a future that will read from both streams,
writing any data read to the opposing stream.
This happens in both directions concurrently.

If an EOF is observed on one stream, [`shutdown()`] will be invoked on
the other, and reading from that stream will stop. Copying of data in
the other direction will continue.

The future will complete successfully once both directions of communication has been shut down.
A direction is shut down when the reader reports EOF,
at which point [`shutdown()`] is called on the corresponding writer. When finished,
it will return a tuple of the number of bytes copied from a to b
and the number of bytes copied from b to a, in that order.

It uses two 8 KB buffers for transferring bytes between `a` and `b` by default.
To set your own buffers sizes use [`copy_bidirectional_with_sizes()`].

[`shutdown()`]: crate::io::AsyncWriteExt::shutdown

### tokio::io::util::copy_bidirectional::copy_bidirectional (function) › Errors

The future will immediately return an error if any IO operation on `a`
or `b` returns an error. Some data read from either stream may be lost (not
written to the other stream) in this case.

### tokio::io::util::copy_bidirectional::copy_bidirectional (function) › Return value

Returns a tuple of bytes copied `a` to `b` and bytes copied `b` to `a`.

## tokio::io::util::copy_bidirectional::copy_bidirectional_with_sizes (function)

Copies data in both directions between `a` and `b` using buffers of the specified size.

This method is the same as the [`copy_bidirectional()`], except that it allows you to set the
size of the internal buffers used when copying data.

## tokio::io::util::copy_buf::copy_buf (function)

Asynchronously copies the entire contents of a reader into a writer.

This function returns a future that will continuously read data from
`reader` and then write it into `writer` in a streaming fashion until
`reader` returns EOF or fails.

On success, the total number of bytes that were copied from `reader` to
`writer` is returned.

This is a [`tokio::io::copy`] alternative for [`AsyncBufRead`] readers
with no extra buffer allocation, since [`AsyncBufRead`] allow access
to the reader's inner buffer.

### tokio::io::util::copy_buf::copy_buf (function) › When to use async alternatives instead of `SyncIoBridge`

If you are looking to use [`std::io::copy`] with a synchronous consumer
(like a `hasher` or compressor), consider using async alternatives instead of
wrapping the reader with [`SyncIoBridge`]. See the [`SyncIoBridge`]
documentation for detailed examples and guidance on hashing, compression,
and data parsing.

[`tokio::io::copy`]: crate::io::copy
[`AsyncBufRead`]: crate::io::AsyncBufRead
[`SyncIoBridge`]: https://docs.rs/tokio-util/latest/tokio_util/io/struct.SyncIoBridge.html

### tokio::io::util::copy_buf::copy_buf (function) › Errors

The returned future will finish with an error will return an error
immediately if any call to `poll_fill_buf` or `poll_write` returns an
error.

### tokio::io::util::copy_buf::copy_buf (function) › Examples

```
use tokio::io;

# async fn dox() -> std::io::Result<()> {
let mut reader: &[u8] = b"hello";
let mut writer: Vec<u8> = vec![];

io::copy_buf(&mut reader, &mut writer).await?;

assert_eq!(b"hello", &writer[..]);
# Ok(())
# }
```

## tokio::io::util::empty::Empty (struct)

`Empty` ignores any data written via [`AsyncWrite`], and will always be empty
(returning zero bytes) when read via [`AsyncRead`].

This struct is generally created by calling [`empty`]. Please see
the documentation of [`empty()`][`empty`] for more details.

This is an asynchronous version of [`std::io::empty`][std].

[`empty`]: fn@empty
[std]: std::io::empty

## tokio::io::util::empty::empty (function)

Creates a value that is always at EOF for reads, and ignores all data written.

All writes on the returned instance will return `Poll::Ready(Ok(buf.len()))`
and the contents of the buffer will not be inspected.

All reads from the returned instance will return `Poll::Ready(Ok(0))`.

This is an asynchronous version of [`std::io::empty`][std].

[std]: std::io::empty

### tokio::io::util::empty::empty (function) › Examples

A slightly sad example of not reading anything into a buffer:

```
use tokio::io::{self, AsyncReadExt};

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
    let mut buffer = String::new();
    io::empty().read_to_string(&mut buffer).await.unwrap();
    assert!(buffer.is_empty());
# }
```

A convoluted way of getting the length of a buffer:

```
use tokio::io::{self, AsyncWriteExt};

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let buffer = vec![1, 2, 3, 5, 8];
let num_bytes = io::empty().write(&buffer).await.unwrap();
assert_eq!(num_bytes, 5);
# }
```

## tokio::io::util::fill_buf::FillBuf (struct)

Future for the [`fill_buf`](crate::io::AsyncBufReadExt::fill_buf) method.

## tokio::io::util::flush::Flush (struct)

A future used to fully flush an I/O object.

Created by the [`AsyncWriteExt::flush`][flush] function.

[flush]: crate::io::AsyncWriteExt::flush

## tokio::io::util::lines::Lines (struct)

Reads lines from an [`AsyncBufRead`].

A `Lines` can be turned into a `Stream` with [`LinesStream`].

This type is usually created using the [`lines`] method.

[`AsyncBufRead`]: crate::io::AsyncBufRead
[`LinesStream`]: https://docs.rs/tokio-stream/0.1/tokio_stream/wrappers/struct.LinesStream.html
[`lines`]: crate::io::AsyncBufReadExt::lines

## tokio::io::util::mem::DuplexStream (struct)

A bidirectional pipe to read and write bytes in memory.

A pair of `DuplexStream`s are created together, and they act as a "channel"
that can be used as in-memory IO types. Writing to one of the pairs will
allow that data to be read from the other, and vice versa.

### tokio::io::util::mem::DuplexStream (struct) › Closing a `DuplexStream`

If one end of the `DuplexStream` channel is dropped, any pending reads on
the other side will continue to read data until the buffer is drained, then
they will signal EOF by returning 0 bytes. Any writes to the other side,
including pending ones (that are waiting for free space in the buffer) will
return `Err(BrokenPipe)` immediately.

### tokio::io::util::mem::DuplexStream (struct) › Example

```
# async fn ex() -> std::io::Result<()> {
# use tokio::io::{AsyncReadExt, AsyncWriteExt};
let (mut client, mut server) = tokio::io::duplex(64);

client.write_all(b"ping").await?;

let mut buf = [0u8; 4];
server.read_exact(&mut buf).await?;
assert_eq!(&buf, b"ping");

server.write_all(b"pong").await?;

client.read_exact(&mut buf).await?;
assert_eq!(&buf, b"pong");
# Ok(())
# }
```

## tokio::io::util::mem::SimplexStream (struct)

A unidirectional pipe to read and write bytes in memory.

It can be constructed by [`simplex`] function which will create a pair of
reader and writer or by calling [`SimplexStream::new_unsplit`] that will
create a handle for both reading and writing.

### tokio::io::util::mem::SimplexStream (struct) › Example

```
# async fn ex() -> std::io::Result<()> {
# use tokio::io::{AsyncReadExt, AsyncWriteExt};
let (mut receiver, mut sender) = tokio::io::simplex(64);

sender.write_all(b"ping").await?;

let mut buf = [0u8; 4];
receiver.read_exact(&mut buf).await?;
assert_eq!(&buf, b"ping");
# Ok(())
# }
```

## tokio::io::util::mem::duplex (function)

Create a new pair of `DuplexStream`s that act like a pair of connected sockets.

The `max_buf_size` argument is the maximum amount of bytes that can be
written to a side before the write returns `Poll::Pending`.

## tokio::io::util::mem::simplex (function)

Creates unidirectional buffer that acts like in memory pipe.

The `max_buf_size` argument is the maximum amount of bytes that can be
written to a buffer before it returns `Poll::Pending`.

### tokio::io::util::mem::simplex (function) › Unify reader and writer

The reader and writer half can be unified into a single structure
of `SimplexStream` that supports both reading and writing or
the `SimplexStream` can be already created as unified structure
using [`SimplexStream::new_unsplit()`].

```
# async fn ex() -> std::io::Result<()> {
# use tokio::io::{AsyncReadExt, AsyncWriteExt};
let (reader, writer) = tokio::io::simplex(64);
let mut simplex_stream = reader.unsplit(writer);
simplex_stream.write_all(b"hello").await?;

let mut buf = [0u8; 5];
simplex_stream.read_exact(&mut buf).await?;
assert_eq!(&buf, b"hello");
# Ok(())
# }
```

## tokio::io::util::read::Read (struct)

A future which can be used to easily read available number of bytes to fill
a buffer.

Created by the [`read`] function.

## tokio::io::util::read_buf::ReadBuf (struct)

Future returned by [`read_buf`](crate::io::AsyncReadExt::read_buf).

## tokio::io::util::read_exact::ReadExact (struct)

Creates a future which will read exactly enough bytes to fill `buf`,
returning an error if EOF is hit sooner.

On success the number of bytes is returned

## tokio::io::util::read_line::ReadLine (struct)

Future for the [`read_line`](crate::io::AsyncBufReadExt::read_line) method.

## tokio::io::util::read_to_string::ReadToString (struct)

Future for the [`read_to_string`](super::AsyncReadExt::read_to_string) method.

## tokio::io::util::read_until::ReadUntil (struct)

Future for the [`read_until`](crate::io::AsyncBufReadExt::read_until) method.
The delimiter is included in the resulting vector.

## tokio::io::util::repeat::Repeat (struct)

An async reader which yields one byte over and over and over and over and
over and...

This struct is generally created by calling [`repeat`][repeat]. Please
see the documentation of `repeat()` for more details.

This is an asynchronous version of [`std::io::Repeat`][std].

[repeat]: fn@repeat
[std]: std::io::Repeat

## tokio::io::util::repeat::repeat (function)

Creates an instance of an async reader that infinitely repeats one byte.

All reads from this reader will succeed by filling the specified buffer with
the given byte.

This is an asynchronous version of [`std::io::repeat`][std].

[std]: std::io::repeat

### tokio::io::util::repeat::repeat (function) › Examples

```
use tokio::io::{self, AsyncReadExt};

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let mut buffer = [0; 3];
io::repeat(0b101).read_exact(&mut buffer).await.unwrap();
assert_eq!(buffer, [0b101, 0b101, 0b101]);
# }
```

## tokio::io::util::shutdown::Shutdown (struct)

A future used to shutdown an I/O object.

Created by the [`AsyncWriteExt::shutdown`][shutdown] function.
[shutdown]: [`crate::io::AsyncWriteExt::shutdown`]

## tokio::io::util::sink::Sink (struct)

An async writer which will move data into the void.

This struct is generally created by calling [`sink`][sink]. Please
see the documentation of `sink()` for more details.

This is an asynchronous version of [`std::io::Sink`][std].

[sink]: sink()
[std]: std::io::Sink

## tokio::io::util::sink::sink (function)

Creates an instance of an async writer which will successfully consume all
data.

All calls to [`poll_write`] on the returned instance will return
`Poll::Ready(Ok(buf.len()))` and the contents of the buffer will not be
inspected.

This is an asynchronous version of [`std::io::sink`][std].

[`poll_write`]: crate::io::AsyncWrite::poll_write()
[std]: std::io::sink

### tokio::io::util::sink::sink (function) › Examples

```
use tokio::io::{self, AsyncWriteExt};

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let buffer = vec![1, 2, 3, 5, 8];
let num_bytes = io::sink().write(&buffer).await?;
assert_eq!(num_bytes, 5);
Ok(())
# }
```

## tokio::io::util::split::Split (struct)

Splitter for the [`split`](crate::io::AsyncBufReadExt::split) method.

A `Split` can be turned into a `Stream` with [`SplitStream`].

[`SplitStream`]: https://docs.rs/tokio-stream/0.1/tokio_stream/wrappers/struct.SplitStream.html

## tokio::io::util::take::Take (struct)

Stream for the [`take`](super::AsyncReadExt::take) method.

## tokio::io::util::write::Write (struct)

A future to write some of the buffer to an `AsyncWrite`.

## tokio::io::util::write_all_buf::WriteAllBuf (struct)

A future to write some of the buffer to an `AsyncWrite`.

## tokio::io::util::write_buf::WriteBuf (struct)

A future to write some of the buffer to an `AsyncWrite`.

## tokio::io::util::write_vectored::WriteVectored (struct)

A future to write a slice of buffers to an `AsyncWrite`.

## tokio::io_driver_fd_deregistered_count (function)

Returns the number of file descriptors that have been deregistered by the
runtime's I/O driver.

### tokio::io_driver_fd_deregistered_count (function) › Examples

```
use tokio::runtime::Handle;

#[tokio::main]
async fn main() {
    let metrics = Handle::current().metrics();

    let n = metrics.io_driver_fd_deregistered_count();
    println!("{} fds have been deregistered by the runtime's I/O driver.", n);
}
```

## tokio::io_driver_fd_registered_count (function)

Returns the number of file descriptors that have been registered with the
runtime's I/O driver.

### tokio::io_driver_fd_registered_count (function) › Examples

```
use tokio::runtime::Handle;

#[tokio::main]
async fn main() {
    let metrics = Handle::current().metrics();

    let registered_fds = metrics.io_driver_fd_registered_count();
    println!("{} fds have been registered with the runtime's I/O driver.", registered_fds);

    let deregistered_fds = metrics.io_driver_fd_deregistered_count();

    let current_fd_count = registered_fds - deregistered_fds;
    println!("{} fds are currently registered by the runtime's I/O driver.", current_fd_count);
}
```

## tokio::io_driver_ready_count (function)

Returns the number of ready events processed by the runtime's
I/O driver.

### tokio::io_driver_ready_count (function) › Examples

```
use tokio::runtime::Handle;

#[tokio::main]
async fn main() {
    let metrics = Handle::current().metrics();

    let n = metrics.io_driver_ready_count();
    println!("{} ready events processed by the runtime's I/O driver.", n);
}
```

## tokio::ip (function)

Return the instruction pointer of this frame.

See the ABI docs for your platform for the exact meaning.

## tokio::is_already_init_err (function)

Whether `SetError` is `SetError::AlreadyInitializedError`.

## tokio::is_at_capacity (function)

Returns `true` if the error was caused by the timer being at capacity.

## tokio::is_cancelled (function)

Returns true if the error was caused by the task being cancelled.

See [the module level docs] for more information on cancellation.

[the module level docs]: crate::task#cancellation

## tokio::is_closed (function)

Checks if a channel is closed.

This method returns `true` if the channel has been closed. The channel is closed
when all [`Sender`] have been dropped, or when [`Receiver::close`] is called.

[`Sender`]: crate::sync::mpsc::Sender
[`Receiver::close`]: crate::sync::mpsc::Receiver::close

### tokio::is_closed (function) › Examples
```
use tokio::sync::mpsc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (_tx, mut rx) = mpsc::channel::<()>(10);
assert!(!rx.is_closed());

rx.close();

assert!(rx.is_closed());
# }
```

## tokio::is_closed (function)

Checks if a channel is closed.

This method returns `true` if the channel has been closed. The channel is closed
when all [`Sender`] have been dropped.

[`Sender`]: crate::sync::broadcast::Sender

### tokio::is_closed (function) › Examples
```
use tokio::sync::broadcast;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, rx) = broadcast::channel::<()>(10);
assert!(!rx.is_closed());

drop(tx);

assert!(rx.is_closed());
# }
```

## tokio::is_closed (function)

Checks if a channel is closed.

This method returns `true` if the channel has been closed. The channel is closed
when all [`UnboundedSender`] have been dropped, or when [`UnboundedReceiver::close`] is called.

[`UnboundedSender`]: crate::sync::mpsc::UnboundedSender
[`UnboundedReceiver::close`]: crate::sync::mpsc::UnboundedReceiver::close

### tokio::is_closed (function) › Examples
```
use tokio::sync::mpsc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (_tx, mut rx) = mpsc::unbounded_channel::<()>();
assert!(!rx.is_closed());

rx.close();

assert!(rx.is_closed());
# }
```

## tokio::is_closed (function)

Checks if the channel has been closed. This happens when all receivers
have dropped.

### tokio::is_closed (function) › Examples

```
let (tx, rx) = tokio::sync::watch::channel(());
assert!(!tx.is_closed());

drop(rx);
assert!(tx.is_closed());
```

## tokio::is_closed (function)

Checks if the channel has been closed. This happens when the
[`Receiver`] is dropped, or when the [`Receiver::close`] method is
called.

[`Receiver`]: crate::sync::mpsc::Receiver
[`Receiver::close`]: crate::sync::mpsc::Receiver::close

```
let (tx, rx) = tokio::sync::mpsc::channel::<()>(42);
assert!(!tx.is_closed());

let tx2 = tx.clone();
assert!(!tx2.is_closed());

drop(rx);
assert!(tx.is_closed());
assert!(tx2.is_closed());
```

## tokio::is_closed (function)

Checks if the channel has been closed. This happens when the
[`UnboundedReceiver`] is dropped, or when the
[`UnboundedReceiver::close`] method is called.

[`UnboundedReceiver`]: crate::sync::mpsc::UnboundedReceiver
[`UnboundedReceiver::close`]: crate::sync::mpsc::UnboundedReceiver::close

```
let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<()>();
assert!(!tx.is_closed());

let tx2 = tx.clone();
assert!(!tx2.is_closed());

drop(rx);
assert!(tx.is_closed());
assert!(tx2.is_closed());
```

## tokio::is_closed (function)

Returns `true` if the associated [`Receiver`] handle has been dropped.

A [`Receiver`] is closed by either calling [`close`] explicitly or the
[`Receiver`] value is dropped.

If `true` is returned, a call to `send` will always result in an error.

[`Receiver`]: Receiver
[`close`]: Receiver::close

### tokio::is_closed (function) › Examples

```
use tokio::sync::oneshot;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, rx) = oneshot::channel();

assert!(!tx.is_closed());

drop(rx);

assert!(tx.is_closed());
assert!(tx.send("never received").is_err());
# }
```

## tokio::is_closed (function)

Returns true if the semaphore is closed

## tokio::is_elapsed (function)

Returns `true` if `Sleep` has elapsed.

A `Sleep` instance is elapsed when the requested duration has elapsed.

## tokio::is_empty (function)

Checks if a channel is empty.

This method returns `true` if the channel has no messages.

### tokio::is_empty (function) › Examples
```
use tokio::sync::mpsc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, rx) = mpsc::channel(10);
assert!(rx.is_empty());

tx.send(0).await.unwrap();
assert!(!rx.is_empty());
# }

```

## tokio::is_empty (function)

Checks if a channel is empty.

This method returns `true` if the channel has no messages.

### tokio::is_empty (function) › Examples
```
use tokio::sync::mpsc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, rx) = mpsc::unbounded_channel();
assert!(rx.is_empty());

tx.send(0).unwrap();
assert!(!rx.is_empty());
# }

```

## tokio::is_empty (function)

Checks if a channel is empty.

This method returns `true` if the channel has no messages.

It is not necessarily safe to poll an empty receiver, which may have
already yielded a value. Use [`is_terminated()`][Self::is_terminated]
to check whether or not a receiver can be safely polled, instead.

### tokio::is_empty (function) › Examples

Sending a value.

```
use tokio::sync::oneshot;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = oneshot::channel();
assert!(rx.is_empty());

tx.send(0).unwrap();
assert!(!rx.is_empty());

let _ = (&mut rx).await;
assert!(rx.is_empty());
# }
```

Dropping the sender.

```
use tokio::sync::oneshot;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = oneshot::channel::<()>();

// A channel is empty if the sender is dropped.
drop(tx);
assert!(rx.is_empty());

// A closed channel still yields an error, however.
(&mut rx).await.expect_err("should yield an error");
assert!(rx.is_empty());
# }
```

Terminated channels are empty.

```should_panic,ignore-wasm
use tokio::sync::oneshot;

#[tokio::main]
async fn main() {
    let (tx, mut rx) = oneshot::channel();
    tx.send(0).unwrap();
    let _ = (&mut rx).await;

    // NB: an empty channel is not necessarily safe to poll!
    assert!(rx.is_empty());
    let _ = (&mut rx).await;
}
```

## tokio::is_empty (function)

Returns true if `Ready` is the empty set.

### tokio::is_empty (function) › Examples

```
use tokio::io::Ready;

assert!(Ready::EMPTY.is_empty());
assert!(!Ready::READABLE.is_empty());
```

## tokio::is_empty (function)

Returns true if there are no queued values.

### tokio::is_empty (function) › Examples

```
use tokio::sync::broadcast;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx1) = broadcast::channel(16);
let mut rx2 = tx.subscribe();

assert!(tx.is_empty());

tx.send(10).unwrap();

assert!(!tx.is_empty());

rx1.recv().await.unwrap();

// The queue is still not empty since rx2 hasn't seen the value.
assert!(!tx.is_empty());

rx2.recv().await.unwrap();

assert!(tx.is_empty());
# }
```

## tokio::is_empty (function)

Returns true if there aren't any messages in the channel that the [`Receiver`]
has yet to receive.

[`Receiver`]: crate::sync::broadcast::Receiver

### tokio::is_empty (function) › Examples

```
use tokio::sync::broadcast;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx1) = broadcast::channel(16);

assert!(rx1.is_empty());

tx.send(10).unwrap();
tx.send(20).unwrap();

assert!(!rx1.is_empty());
assert_eq!(rx1.recv().await.unwrap(), 10);
assert_eq!(rx1.recv().await.unwrap(), 20);
assert!(rx1.is_empty());
# }
```

## tokio::is_empty (function)

Returns whether the `JoinSet` is empty.

## tokio::is_error (function)

Returns `true` if the value includes error `readiness`.

### tokio::is_error (function) › Examples

```
use tokio::io::Ready;

assert!(!Ready::EMPTY.is_error());
assert!(!Ready::WRITABLE.is_error());
assert!(Ready::ERROR.is_error());
```

## tokio::is_error (function)

Returns true if the value includes error interest.

### tokio::is_error (function) › Examples

```
use tokio::io::Interest;

assert!(Interest::ERROR.is_error());
assert!(!Interest::WRITABLE.is_error());

let combined = Interest::READABLE | Interest::ERROR;
assert!(combined.is_error());
```

## tokio::is_finished (function)

Checks if the task associated with this `AbortHandle` has finished.

Please note that this method can return `false` even if `abort` has been
called on the task. This is because the cancellation process may take
some time, and this method does not return `true` until it has
completed.

## tokio::is_finished (function)

Checks if the task associated with this `JoinHandle` has finished.

Please note that this method can return `false` even if [`abort`] has been
called on the task. This is because the cancellation process may take
some time, and this method does not return `true` until it has
completed.

```rust
use tokio::time;

# #[tokio::main(flavor = "current_thread", start_paused = true)]
# async fn main() {
let handle1 = tokio::spawn(async {
    // do some stuff here
});
let handle2 = tokio::spawn(async {
    // do some other stuff here
    time::sleep(time::Duration::from_secs(10)).await;
});
// Wait for the task to finish
handle2.abort();
time::sleep(time::Duration::from_secs(1)).await;
assert!(handle1.is_finished());
assert!(handle2.is_finished());
# }
```
[`abort`]: method@JoinHandle::abort

## tokio::is_initializing_err (function)

Whether `SetError` is `SetError::InitializingError`

## tokio::is_invalid (function)

Returns `true` if the error was caused by the timer being misconfigured.

## tokio::is_leader (function)

Returns `true` if this task from wait is the "leader task".

Only one task will have `true` returned from their result, all other tasks will have
`false` returned.

## tokio::is_missing_context (function)

Returns true if the call failed because there is currently no runtime in
the Tokio context.

## tokio::is_pair_of (function)

Checks if this `ReadHalf` and some `WriteHalf` were split from the same
stream.

## tokio::is_pair_of (function)

Checks if this `WriteHalf` and some `ReadHalf` were split from the same
stream.

## tokio::is_panic (function)

Returns true if the error was caused by the task panicking.

### tokio::is_panic (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use std::panic;

#[tokio::main]
async fn main() {
    let err = tokio::spawn(async {
        panic!("boom");
    }).await.unwrap_err();

    assert!(err.is_panic());
}
# }
```

## tokio::is_priority (function)

Returns `true` if the value includes priority `readiness`.

### tokio::is_priority (function) › Examples

```
use tokio::io::Ready;

assert!(!Ready::EMPTY.is_priority());
assert!(!Ready::WRITABLE.is_priority());
assert!(Ready::PRIORITY.is_priority());
```

## tokio::is_priority (function)

Returns true if the value includes priority interest.

### tokio::is_priority (function) › Examples

```
use tokio::io::Interest;

assert!(!Interest::READABLE.is_priority());
assert!(Interest::PRIORITY.is_priority());

let both = Interest::READABLE | Interest::PRIORITY;
assert!(both.is_priority());
```

## tokio::is_read_closed (function)

Returns `true` if the value includes read-closed `readiness`.

### tokio::is_read_closed (function) › Examples

```
use tokio::io::Ready;

assert!(!Ready::EMPTY.is_read_closed());
assert!(!Ready::READABLE.is_read_closed());
assert!(Ready::READ_CLOSED.is_read_closed());
```

## tokio::is_readable (function)

Returns `true` if the value includes `readable`.

### tokio::is_readable (function) › Examples

```
use tokio::io::Ready;

assert!(!Ready::EMPTY.is_readable());
assert!(Ready::READABLE.is_readable());
assert!(Ready::READ_CLOSED.is_readable());
assert!(!Ready::WRITABLE.is_readable());
```

## tokio::is_readable (function)

Returns true if the value includes readable interest.

### tokio::is_readable (function) › Examples

```
use tokio::io::Interest;

assert!(Interest::READABLE.is_readable());
assert!(!Interest::WRITABLE.is_readable());

let both = Interest::READABLE | Interest::WRITABLE;
assert!(both.is_readable());
```

## tokio::is_shutdown (function)

Returns `true` if the error was caused by the timer being shutdown.

## tokio::is_terminated (function)

Checks if this receiver is terminated.

This function returns true if this receiver has already yielded a [`Poll::Ready`] result.
If so, this receiver should no longer be polled.

### tokio::is_terminated (function) › Examples

Sending a value and polling it.

```
use tokio::sync::oneshot;

use std::task::Poll;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = oneshot::channel();

// A receiver is not terminated when it is initialized.
assert!(!rx.is_terminated());

// A receiver is not terminated it is polled and is still pending.
let poll = futures::poll!(&mut rx);
assert_eq!(poll, Poll::Pending);
assert!(!rx.is_terminated());

// A receiver is not terminated if a value has been sent, but not yet read.
tx.send(0).unwrap();
assert!(!rx.is_terminated());

// A receiver *is* terminated after it has been polled and yielded a value.
assert_eq!((&mut rx).await, Ok(0));
assert!(rx.is_terminated());
# }
```

Dropping the sender.

```
use tokio::sync::oneshot;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = oneshot::channel::<()>();

// A receiver is not immediately terminated when the sender is dropped.
drop(tx);
assert!(!rx.is_terminated());

// A receiver *is* terminated after it has been polled and yielded an error.
let _ = (&mut rx).await.unwrap_err();
assert!(rx.is_terminated());
# }
```

## tokio::is_thread_local_destroyed (function)

Returns true if the call failed because the Tokio context thread-local
had been destroyed. This can usually only happen if in the destructor of
other thread-locals.

## tokio::is_unnamed (function)

Returns `true` if the address is unnamed.

Documentation reflected in [`SocketAddr`].

[`SocketAddr`]: std::os::unix::net::SocketAddr

## tokio::is_writable (function)

Returns `true` if the value includes writable `readiness`.

### tokio::is_writable (function) › Examples

```
use tokio::io::Ready;

assert!(!Ready::EMPTY.is_writable());
assert!(!Ready::READABLE.is_writable());
assert!(Ready::WRITABLE.is_writable());
assert!(Ready::WRITE_CLOSED.is_writable());
```

## tokio::is_writable (function)

Returns true if the value includes writable interest.

### tokio::is_writable (function) › Examples

```
use tokio::io::Interest;

assert!(!Interest::READABLE.is_writable());
assert!(Interest::WRITABLE.is_writable());

let both = Interest::READABLE | Interest::WRITABLE;
assert!(both.is_writable());
```

## tokio::is_write_closed (function)

Returns `true` if the value includes write-closed `readiness`.

### tokio::is_write_closed (function) › Examples

```
use tokio::io::Ready;

assert!(!Ready::EMPTY.is_write_closed());
assert!(!Ready::WRITABLE.is_write_closed());
assert!(Ready::WRITE_CLOSED.is_write_closed());
```

## tokio::is_write_vectored (function)

Determines if this writer has an efficient [`poll_write_vectored`]
implementation.

If a writer does not override the default [`poll_write_vectored`]
implementation, code using it may want to avoid the method all together
and coalesce writes into a single buffer for higher performance.

The default implementation returns `false`.

[`poll_write_vectored`]: AsyncWrite::poll_write_vectored

## tokio::iter (function)

Iterate over tasks.

## tokio::join (macro)

Waits on multiple concurrent branches, returning when **all** branches
complete.

The `join!` macro must be used inside of async functions, closures, and
blocks.

The `join!` macro takes a list of async expressions and evaluates them
concurrently on the same task. Each async expression evaluates to a future
and the futures from each expression are multiplexed on the current task.

When working with async expressions returning `Result`, `join!` will wait
for **all** branches complete regardless if any complete with `Err`. Use
[`try_join!`] to return early when `Err` is encountered.

[`try_join!`]: crate::try_join

### tokio::join (macro) › Notes

The supplied futures are stored inline and do not require allocating a
`Vec`.

### tokio::join (macro) › Runtime characteristics

By running all async expressions on the current task, the expressions are
able to run **concurrently** but not in **parallel**. This means all
expressions are run on the same thread and if one branch blocks the thread,
all other expressions will be unable to continue. If parallelism is
required, spawn each async expression using [`tokio::spawn`] and pass the
join handle to `join!`.

[`tokio::spawn`]: crate::spawn

### tokio::join (macro) › Fairness

By default, `join!`'s generated future rotates which contained
future is polled first whenever it is woken.

This behavior can be overridden by adding `biased;` to the beginning of the
macro usage. See the examples for details. This will cause `join` to poll
the futures in the order they appear from top to bottom.

You may want this if your futures may interact in a way where known polling order is significant.

But there is an important caveat to this mode. It becomes your responsibility
to ensure that the polling order of your futures is fair. If for example you
are joining a stream and a shutdown future, and the stream has a
huge volume of messages that takes a long time to finish processing per poll, you should
place the shutdown future earlier in the `join!` list to ensure that it is
always polled, and will not be delayed due to the stream future taking a long time to return
`Poll::Pending`.

### tokio::join (macro) › Examples

Basic join with two branches

```
async fn do_stuff_async() {
    // async work
}

async fn more_async_work() {
    // more here
}

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (first, second) = tokio::join!(
    do_stuff_async(),
    more_async_work());

// do something with the values
# }
```

Using the `biased;` mode to control polling order.

```
# #[cfg(not(target_family = "wasm"))]
# {
async fn do_stuff_async() {
    // async work
}

async fn more_async_work() {
    // more here
}

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (first, second) = tokio::join!(
    biased;
    do_stuff_async(),
    more_async_work()
);

// do something with the values
# }
# }
```

## tokio::join_all (function)

Awaits the completion of all tasks in this `JoinSet`, returning a vector of their results.

The results will be stored in the order they completed not the order they were spawned.
This is a convenience method that is equivalent to calling [`join_next`] in
a loop. If any tasks on the `JoinSet` fail with an [`JoinError`], then this call
to `join_all` will panic and all remaining tasks on the `JoinSet` are
cancelled. To handle errors in any other way, manually call [`join_next`]
in a loop.

### tokio::join_all (function) › Examples

Spawn multiple tasks and `join_all` them.

```
use tokio::task::JoinSet;
use std::time::Duration;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let mut set = JoinSet::new();

for i in 0..3 {
    set.spawn(async move {
        tokio::time::sleep(Duration::from_secs(3 - i)).await;
        i
    });
}

let output = set.join_all().await;
assert_eq!(output, vec![2, 1, 0]);
# }
```

Equivalent implementation of `join_all`, using [`join_next`] and loop.

```
use tokio::task::JoinSet;
use std::panic;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let mut set = JoinSet::new();

for i in 0..3 {
    set.spawn(async move {i});
}

let mut output = Vec::new();
while let Some(res) = set.join_next().await{
    match res {
        Ok(t) => output.push(t),
        Err(err) if err.is_panic() => panic::resume_unwind(err.into_panic()),
        Err(err) => panic!("{err}"),
    }
}
assert_eq!(output.len(),3);
# }
```
[`join_next`]: fn@Self::join_next
[`JoinError::id`]: fn@crate::task::JoinError::id

## tokio::join_multicast_v4 (function)

Executes an operation of the `IP_ADD_MEMBERSHIP` type.

This function specifies a new multicast group for this socket to join.
The address must be a valid multicast address, and `interface` is the
address of the local interface with which the system should join the
multicast group. If it's equal to `INADDR_ANY` then an appropriate
interface is chosen by the system.

## tokio::join_multicast_v6 (function)

Executes an operation of the `IPV6_ADD_MEMBERSHIP` type.

This function specifies a new multicast group for this socket to join.
The address must be a valid multicast address, and `interface` is the
index of the interface to join/leave (or 0 to indicate any interface).

## tokio::join_next (function)

Waits until one of the tasks in the set completes and returns its output.

Returns `None` if the set is empty.

### tokio::join_next (function) › Cancel safety

This method is cancel safe. If `join_next` is used as a branch in
`tokio::select!` and another branch completes first, it is guaranteed
that no tasks were removed from this `JoinSet`.

## tokio::join_next_with_id (function)

Waits until one of the tasks in the set completes and returns its
output, along with the [task ID] of the completed task.

Returns `None` if the set is empty.

When this method returns an error, then the id of the task that failed can be accessed
using the [`JoinError::id`] method.

### tokio::join_next_with_id (function) › Cancel safety

This method is cancel safe. If `join_next_with_id` is used as a branch
in `tokio::select!` and another branch completes first, it is
guaranteed that no tasks were removed from this `JoinSet`.

[task ID]: crate::task::Id
[`JoinError::id`]: fn@crate::task::JoinError::id

## tokio::keepalive (function)

Gets the value of the `SO_KEEPALIVE` option on this socket.

## tokio::kill (function)

Forces the child to exit.

This is equivalent to sending a `SIGKILL` on unix platforms
followed by [`wait`](Child::wait).

Note: std version of [`Child::kill`](std::process::Child::kill) does not `wait`.
For an equivalent of `Child::kill` in the standard library,
use [`start_kill`](Child::start_kill).

### tokio::kill (function) › Examples

If the child has to be killed remotely, it is possible to do it using
a combination of the select! macro and a `oneshot` channel. In the following
example, the child will run until completion unless a message is sent on
the `oneshot` channel. If that happens, the child is killed immediately
using the `.kill()` method.

```no_run
use tokio::process::Command;
use tokio::sync::oneshot::channel;

#[tokio::main]
async fn main() {
    let (send, recv) = channel::<()>();
    let mut child = Command::new("sleep").arg("1").spawn().unwrap();
    tokio::spawn(async move { send.send(()) });
    tokio::select! {
        _ = child.wait() => {}
        _ = recv => child.kill().await.expect("kill failed"),
    }
}
```

You can also interact with the child's standard I/O. For example, you can
read its stdout while waiting for it to exit.

```no_run
# use std::process::Stdio;
#
# use tokio::io::AsyncReadExt;
# use tokio::process::Command;
# use tokio::sync::oneshot::channel;

#[tokio::main]
async fn main() {
    let (_tx, rx) = channel::<()>();

    let mut child = Command::new("echo")
        .arg("Hello World!")
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();

    let mut stdout = child.stdout.take().expect("stdout is not captured");

    let read_stdout = tokio::spawn(async move {
        let mut buff = Vec::new();
        let _ = stdout.read_to_end(&mut buff).await;

        buff
    });

    tokio::select! {
        _ = child.wait() => {}
        _ = rx => { child.kill().await.expect("kill failed") },
    }

    let buff = read_stdout.await.unwrap();

    assert_eq!(buff, b"Hello World!\n");
}
```

## tokio::kill_on_drop (function)

Controls whether a `kill` operation should be invoked on a spawned child
process when its corresponding `Child` handle is dropped.

By default, this value is assumed to be `false`, meaning the next spawned
process will not be killed on drop, similar to the behavior of the standard
library.

### tokio::kill_on_drop (function) › Caveats

On Unix platforms processes must be "reaped" by their parent process after
they have exited in order to release all OS resources. A child process which
has exited, but has not yet been reaped by its parent is considered a "zombie"
process. Such processes continue to count against limits imposed by the system,
and having too many zombie processes present can prevent additional processes
from being spawned.

Although issuing a `kill` signal to the child process is a synchronous
operation, the resulting zombie process cannot be `.await`ed inside of the
destructor to avoid blocking other tasks. The tokio runtime will, on a
best-effort basis, attempt to reap and clean up such processes in the
background, but no additional guarantees are made with regard to
how quickly or how often this procedure will take place.

If stronger guarantees are required, it is recommended to avoid dropping
a [`Child`] handle where possible, and instead utilize `child.wait().await`
or `child.kill().await` where possible.

## tokio::leave_multicast_v4 (function)

Executes an operation of the `IP_DROP_MEMBERSHIP` type.

For more information about this option, see [`join_multicast_v4`].

[`join_multicast_v4`]: method@Self::join_multicast_v4

## tokio::leave_multicast_v6 (function)

Executes an operation of the `IPV6_DROP_MEMBERSHIP` type.

For more information about this option, see [`join_multicast_v6`].

[`join_multicast_v6`]: method@Self::join_multicast_v6

## tokio::len (function)

Returns the number of messages in the channel.

### tokio::len (function) › Examples
```
use tokio::sync::mpsc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, rx) = mpsc::channel(10);
assert_eq!(0, rx.len());

tx.send(0).await.unwrap();
assert_eq!(1, rx.len());
# }
```

## tokio::len (function)

Returns the number of messages in the channel.

### tokio::len (function) › Examples
```
use tokio::sync::mpsc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, rx) = mpsc::unbounded_channel();
assert_eq!(0, rx.len());

tx.send(0).unwrap();
assert_eq!(1, rx.len());
# }
```

## tokio::len (function)

Returns the number of messages that were sent into the channel and that
this [`Receiver`] has yet to receive.

This count includes messages that have already been overwritten in the
ring buffer and are no longer readable. If `len` is **greater than** the
channel's effective capacity (the provided capacity rounded up to the
next power of two), the next call to [`recv`] returns
`Err(RecvError::Lagged)` and the next call to [`try_recv`] returns
`Err(TryRecvError::Lagged)`. For example, with `channel(10)` the buffer
length is 16, so lagging begins once `len` is larger than 16.

After a successful receive (including after handling `Lagged` and then
reading retained messages), `len` decreases accordingly.

[`Receiver`]: crate::sync::broadcast::Receiver
[`recv`]: crate::sync::broadcast::Receiver::recv
[`try_recv`]: crate::sync::broadcast::Receiver::try_recv

### tokio::len (function) › Examples

```
use tokio::sync::broadcast;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx1) = broadcast::channel(16);

tx.send(10).unwrap();
tx.send(20).unwrap();

assert_eq!(rx1.len(), 2);
assert_eq!(rx1.recv().await.unwrap(), 10);
assert_eq!(rx1.len(), 1);
assert_eq!(rx1.recv().await.unwrap(), 20);
assert_eq!(rx1.len(), 0);
# }
```

## tokio::len (function)

Returns the number of queued values.

A value is queued until it has either been seen by all receivers that were alive at the time
it was sent, or has been evicted from the queue by subsequent sends that exceeded the
queue's capacity.

### tokio::len (function) › Note

In contrast to [`Receiver::len`], this method only reports queued values and not values that
have been evicted from the queue before being seen by all receivers.

### tokio::len (function) › Examples

```
use tokio::sync::broadcast;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx1) = broadcast::channel(16);
let mut rx2 = tx.subscribe();

tx.send(10).unwrap();
tx.send(20).unwrap();
tx.send(30).unwrap();

assert_eq!(tx.len(), 3);

rx1.recv().await.unwrap();

// The len is still 3 since rx2 hasn't seen the first value yet.
assert_eq!(tx.len(), 3);

rx2.recv().await.unwrap();

assert_eq!(tx.len(), 2);
# }
```

## tokio::len (function)

Returns the number of tasks currently in the `JoinSet`.

## tokio::limit (function)

Returns the remaining number of bytes that can be
read before this instance will return EOF.

### tokio::limit (function) › Note

This instance may reach `EOF` after reading fewer bytes than indicated by
this method if the underlying [`AsyncRead`] instance reaches EOF.

## tokio::linear (function)

Create a linear bucketed histogram

### tokio::linear (function) › Arguments

* `bucket_width`: The width of each bucket
* `num_buckets`: The number of buckets

## tokio::lineno (function)

Returns the line number for where this symbol is currently executing.

If debuginfo is missing, this is likely to return `None`.

## tokio::lines (function)

Returns a stream over the lines of this reader.
This method is the async equivalent to [`BufRead::lines`](std::io::BufRead::lines).

The stream returned from this function will yield instances of
[`io::Result`]`<`[`Option`]`<`[`String`]`>>`. Each string returned will *not* have a newline
byte (the 0xA byte) or `CRLF` (0xD, 0xA bytes) at the end.

[`io::Result`]: std::io::Result
[`Option`]: core::option::Option
[`String`]: String

### tokio::lines (function) › Errors

Each line of the stream has the same error semantics as [`AsyncBufReadExt::read_line`].

### tokio::lines (function) › Examples

[`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
this example, we use [`Cursor`] to iterate over all the lines in a byte
slice.

[`Cursor`]: std::io::Cursor

```
use tokio::io::AsyncBufReadExt;

use std::io::Cursor;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let cursor = Cursor::new(b"lorem\nipsum\r\ndolor");

let mut lines = cursor.lines();

assert_eq!(lines.next_line().await.unwrap(), Some(String::from("lorem")));
assert_eq!(lines.next_line().await.unwrap(), Some(String::from("ipsum")));
assert_eq!(lines.next_line().await.unwrap(), Some(String::from("dolor")));
assert_eq!(lines.next_line().await.unwrap(), None);
# }
```

[`AsyncBufReadExt::read_line`]: AsyncBufReadExt::read_line

## tokio::linger (function)

Reads the linger duration for this socket by getting the `SO_LINGER`
option.

For more information about this option, see [`set_zero_linger`] and [`set_linger`].

[`set_linger`]: TcpSocket::set_linger
[`set_zero_linger`]: TcpSocket::set_zero_linger

## tokio::linger (function)

Reads the linger duration for this socket by getting the `SO_LINGER`
option.

For more information about this option, see [`set_zero_linger`] and [`set_linger`].

[`set_linger`]: TcpStream::set_linger
[`set_zero_linger`]: TcpStream::set_zero_linger

### tokio::linger (function) › Examples

```no_run
use tokio::net::TcpStream;

# async fn dox() -> Result<(), Box<dyn std::error::Error>> {
let stream = TcpStream::connect("127.0.0.1:8080").await?;

println!("{:?}", stream.linger()?);
# Ok(())
# }
```

## tokio::listen (function)

Converts the socket into a `TcpListener`.

`backlog` defines the maximum number of pending connections are queued
by the operating system at any given time. Connection are removed from
the queue with [`TcpListener::accept`]. When the queue is full, the
operating-system will start rejecting connections.

[`TcpListener::accept`]: TcpListener::accept

This calls the `listen(2)` operating-system function, marking the socket
as a passive socket. Behavior is platform specific. Refer to the target
platform's documentation for more details.

### tokio::listen (function) › Examples

Create a `TcpListener`.

```no_run
use tokio::net::TcpSocket;

use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let addr = "127.0.0.1:8080".parse().unwrap();

    let socket = TcpSocket::new_v4()?;
    socket.bind(addr)?;

    let listener = socket.listen(1024)?;
# drop(listener);

    Ok(())
}
```

## tokio::listen (function)

Converts the socket into a `UnixListener`.

`backlog` defines the maximum number of pending connections are queued
by the operating system at any given time. Connection are removed from
the queue with [`UnixListener::accept`]. When the queue is full, the
operating-system will start rejecting connections.

Calling this function on a socket created by [`new_datagram`] will return an error.

This calls the `listen(2)` operating-system function, marking the socket
as a passive socket.

[`new_datagram`]: `UnixSocket::new_datagram`

## tokio::local_addr (function)

Gets the local address of this socket.

Will fail on windows if called before `bind`.

### tokio::local_addr (function) › Examples

```no_run
use tokio::net::TcpSocket;

use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let addr = "127.0.0.1:8080".parse().unwrap();

    let socket = TcpSocket::new_v4()?;
    socket.bind(addr)?;
    assert_eq!(socket.local_addr().unwrap().to_string(), "127.0.0.1:8080");
    let listener = socket.listen(1024)?;
    Ok(())
}
```

## tokio::local_addr (function)

Returns the local address that this listener is bound to.

This can be useful, for example, when binding to port 0 to figure out
which port was actually bound.

### tokio::local_addr (function) › Examples

```rust,no_run
use tokio::net::TcpListener;

use std::io;
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};

#[tokio::main]
async fn main() -> io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:8080").await?;

    assert_eq!(listener.local_addr()?,
               SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));

    Ok(())
}
```

## tokio::local_addr (function)

Returns the local address that this socket is bound to.

### tokio::local_addr (function) › Example

```no_run
use tokio::net::UdpSocket;
# use std::{io, net::SocketAddr};

# #[tokio::main]
# async fn main() -> io::Result<()> {
let addr = "0.0.0.0:8080".parse::<SocketAddr>().unwrap();
let sock = UdpSocket::bind(addr).await?;
// the address the socket is bound to
let local_addr = sock.local_addr()?;
# Ok(())
# }
```

## tokio::local_addr (function)

Returns the local address that this stream is bound to.

## tokio::local_addr (function)

Returns the local address that this stream is bound to.

## tokio::local_addr (function)

Returns the local address that this stream is bound to.

## tokio::local_addr (function)

Returns the local address that this stream is bound to.

## tokio::local_addr (function)

Returns the local address that this stream is bound to.

### tokio::local_addr (function) › Examples

```no_run
use tokio::net::TcpStream;

# async fn dox() -> Result<(), Box<dyn std::error::Error>> {
let stream = TcpStream::connect("127.0.0.1:8080").await?;

println!("{:?}", stream.local_addr()?);
# Ok(())
# }
```

## tokio::local_addr (function)

Returns the local socket address of this listener.

## tokio::local_addr (function)

Returns the socket address of the local half of this connection.

## tokio::local_addr (function)

Returns the socket address of the local half of this connection.

## tokio::local_addr (function)

Returns the socket address of the local half of this connection.

## tokio::local_addr (function)

Returns the socket address of the local half of this connection.

## tokio::local_addr (function)

Returns the socket address of the local half of this connection.

### tokio::local_addr (function) › Examples

```no_run
use tokio::net::UnixStream;

# async fn dox() -> Result<(), Box<dyn std::error::Error>> {
let dir = tempfile::tempdir().unwrap();
let bind_path = dir.path().join("bind_path");
let stream = UnixStream::connect(bind_path).await?;

println!("{:?}", stream.local_addr()?);
# Ok(())
# }
```

## tokio::lock (function)

Locks this mutex, causing the current task to yield until the lock has
been acquired.  When the lock has been acquired, function returns a
[`MutexGuard`].

If the mutex is available to be acquired immediately, then this call
will typically not yield to the runtime. However, this is not guaranteed
under all circumstances.

### tokio::lock (function) › Cancel safety

This method uses a queue to fairly distribute locks in the order they
were requested. Cancelling a call to `lock` makes you lose your place in
the queue.

### tokio::lock (function) › Examples

```
use tokio::sync::Mutex;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let mutex = Mutex::new(1);

let mut n = mutex.lock().await;
*n = 2;
# }
```

## tokio::lock_owned (function)

Locks this mutex, causing the current task to yield until the lock has
been acquired. When the lock has been acquired, this returns an
[`OwnedMutexGuard`].

If the mutex is available to be acquired immediately, then this call
will typically not yield to the runtime. However, this is not guaranteed
under all circumstances.

This method is identical to [`Mutex::lock`], except that the returned
guard references the `Mutex` with an [`Arc`] rather than by borrowing
it. Therefore, the `Mutex` must be wrapped in an `Arc` to call this
method, and the guard will live for the `'static` lifetime, as it keeps
the `Mutex` alive by holding an `Arc`.

### tokio::lock_owned (function) › Cancel safety

This method uses a queue to fairly distribute locks in the order they
were requested. Cancelling a call to `lock_owned` makes you lose your
place in the queue.

### tokio::lock_owned (function) › Examples

```
use tokio::sync::Mutex;
use std::sync::Arc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let mutex = Arc::new(Mutex::new(1));

let mut n = mutex.clone().lock_owned().await;
*n = 2;
# }
```

[`Arc`]: std::sync::Arc

## tokio::log (function)

Creates a log-scaled bucketed histogram

See [`LogHistogramBuilder`] for information about configuration & defaults

## tokio::made_progress (function)

Signals that the task that obtained this `RestoreOnPending` was able to make
progress. This prevents the task budget from being restored to the value
it had prior to obtaining this instance when it is dropped.

## tokio::map (function)

Makes a new [`MappedMutexGuard`] for a component of the locked data.

This operation cannot fail as the [`MappedMutexGuard`] passed in already locked the mutex.

This is an associated function that needs to be used as `MappedMutexGuard::map(...)`. A
method would interfere with methods of the same name on the contents of the locked data.

[`MappedMutexGuard`]: struct@MappedMutexGuard

## tokio::map (function)

Makes a new [`MappedMutexGuard`] for a component of the locked data.

This operation cannot fail as the [`MutexGuard`] passed in already locked the mutex.

This is an associated function that needs to be used as `MutexGuard::map(...)`. A method
would interfere with methods of the same name on the contents of the locked data.

### tokio::map (function) › Examples

```
use tokio::sync::{Mutex, MutexGuard};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Foo(u32);

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let foo = Mutex::new(Foo(1));

{
    let mut mapped = MutexGuard::map(foo.lock().await, |f| &mut f.0);
    *mapped = 2;
}

assert_eq!(Foo(2), *foo.lock().await);
# }
```

[`MutexGuard`]: struct@MutexGuard
[`MappedMutexGuard`]: struct@MappedMutexGuard

## tokio::map (function)

Makes a new [`OwnedMappedMutexGuard`] for a component of the locked data.

This operation cannot fail as the [`OwnedMappedMutexGuard`] passed in already locked the mutex.

This is an associated function that needs to be used as `OwnedMappedMutexGuard::map(...)`. A method
would interfere with methods of the same name on the contents of the locked data.

[`OwnedMappedMutexGuard`]: struct@OwnedMappedMutexGuard

## tokio::map (function)

Makes a new [`OwnedMappedMutexGuard`] for a component of the locked data.

This operation cannot fail as the [`OwnedMutexGuard`] passed in already locked the mutex.

This is an associated function that needs to be used as `OwnedMutexGuard::map(...)`. A method
would interfere with methods of the same name on the contents of the locked data.

### tokio::map (function) › Examples

```
use tokio::sync::{Mutex, OwnedMutexGuard};
use std::sync::Arc;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Foo(u32);

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let foo = Arc::new(Mutex::new(Foo(1)));

{
    let mut mapped = OwnedMutexGuard::map(foo.clone().lock_owned().await, |f| &mut f.0);
    *mapped = 2;
}

assert_eq!(Foo(2), *foo.lock().await);
# }
```

[`OwnedMutexGuard`]: struct@OwnedMutexGuard
[`OwnedMappedMutexGuard`]: struct@OwnedMappedMutexGuard

## tokio::map (function)

Makes a new [`OwnedRwLockMappedWriteGuard`] for a component of the locked
data.

This operation cannot fail as the `OwnedRwLockWriteGuard` passed in
already locked the data.

This is an associated function that needs to be used as
`OwnedRwLockWriteGuard::map(..)`. A method would interfere with methods
of the same name on the contents of the locked data.

### tokio::map (function) › Examples

```
use std::sync::Arc;
use tokio::sync::{RwLock, OwnedRwLockWriteGuard};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Foo(u32);

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let lock = Arc::new(RwLock::new(Foo(1)));

{
    let lock = Arc::clone(&lock);
    let mut mapped = OwnedRwLockWriteGuard::map(lock.write_owned().await, |f| &mut f.0);
    *mapped = 2;
}

assert_eq!(Foo(2), *lock.read().await);
# }
```

## tokio::map (function)

Makes a new [`RwLockMappedWriteGuard`] for a component of the locked data.

This operation cannot fail as the `RwLockWriteGuard` passed in already
locked the data.

This is an associated function that needs to be used as
`RwLockWriteGuard::map(..)`. A method would interfere with methods of
the same name on the contents of the locked data.

This is an asynchronous version of [`RwLockWriteGuard::map`] from the
[`parking_lot` crate].

[`RwLockMappedWriteGuard`]: struct@crate::sync::RwLockMappedWriteGuard
[`RwLockWriteGuard::map`]: https://docs.rs/lock_api/latest/lock_api/struct.RwLockWriteGuard.html#method.map
[`parking_lot` crate]: https://crates.io/crates/parking_lot

### tokio::map (function) › Examples

```
use tokio::sync::{RwLock, RwLockWriteGuard};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Foo(u32);

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let lock = RwLock::new(Foo(1));

{
    let mut mapped = RwLockWriteGuard::map(lock.write().await, |f| &mut f.0);
    *mapped = 2;
}

assert_eq!(Foo(2), *lock.read().await);
# }
```

## tokio::map (function)

Makes a new `OwnedRwLockMappedWriteGuard` for a component of the locked
data.

This operation cannot fail as the `OwnedRwLockMappedWriteGuard` passed
in already locked the data.

This is an associated function that needs to be used as
`OwnedRwLockWriteGuard::map(..)`. A method would interfere with methods
of the same name on the contents of the locked data.

### tokio::map (function) › Examples

```
use std::sync::Arc;
use tokio::sync::{RwLock, OwnedRwLockWriteGuard};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Foo(u32);

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let lock = Arc::new(RwLock::new(Foo(1)));

{
    let lock = Arc::clone(&lock);
    let mut mapped = OwnedRwLockWriteGuard::map(lock.write_owned().await, |f| &mut f.0);
    *mapped = 2;
}

assert_eq!(Foo(2), *lock.read().await);
# }
```

## tokio::map (function)

Makes a new `OwnedRwLockReadGuard` for a component of the locked data.
This operation cannot fail as the `OwnedRwLockReadGuard` passed in
already locked the data.

This is an associated function that needs to be
used as `OwnedRwLockReadGuard::map(...)`. A method would interfere with
methods of the same name on the contents of the locked data.

### tokio::map (function) › Examples

```
use std::sync::Arc;
use tokio::sync::{RwLock, OwnedRwLockReadGuard};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Foo(u32);

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let lock = Arc::new(RwLock::new(Foo(1)));

let guard = lock.read_owned().await;
let guard = OwnedRwLockReadGuard::map(guard, |f| &f.0);

assert_eq!(1, *guard);
# }
```

## tokio::map (function)

Makes a new `RwLockMappedWriteGuard` for a component of the locked data.

This operation cannot fail as the `RwLockMappedWriteGuard` passed in already
locked the data.

This is an associated function that needs to be used as
`RwLockMappedWriteGuard::map(..)`. A method would interfere with methods
of the same name on the contents of the locked data.

This is an asynchronous version of [`RwLockWriteGuard::map`] from the
[`parking_lot` crate].

[`RwLockWriteGuard::map`]: https://docs.rs/lock_api/latest/lock_api/struct.RwLockWriteGuard.html#method.map
[`parking_lot` crate]: https://crates.io/crates/parking_lot

### tokio::map (function) › Examples

```
use tokio::sync::{RwLock, RwLockWriteGuard};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Foo(u32);

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let lock = RwLock::new(Foo(1));

{
    let mut mapped = RwLockWriteGuard::map(lock.write().await, |f| &mut f.0);
    *mapped = 2;
}

assert_eq!(Foo(2), *lock.read().await);
# }
```

## tokio::map (function)

Makes a new `RwLockReadGuard` for a component of the locked data.

This operation cannot fail as the `RwLockReadGuard` passed in already
locked the data.

This is an associated function that needs to be
used as `RwLockReadGuard::map(...)`. A method would interfere with
methods of the same name on the contents of the locked data.

This is an asynchronous version of [`RwLockReadGuard::map`] from the
[`parking_lot` crate].

[`RwLockReadGuard::map`]: https://docs.rs/lock_api/latest/lock_api/struct.RwLockReadGuard.html#method.map
[`parking_lot` crate]: https://crates.io/crates/parking_lot

### tokio::map (function) › Examples

```
use tokio::sync::{RwLock, RwLockReadGuard};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Foo(u32);

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let lock = RwLock::new(Foo(1));

let guard = lock.read().await;
let guard = RwLockReadGuard::map(guard, |f| &f.0);

assert_eq!(1, *guard);
# }
```

## tokio::mark_changed (function)

Marks the state as changed.

After invoking this method [`has_changed()`](Self::has_changed)
returns `true` and [`changed()`](Self::changed) returns
immediately, regardless of whether a new value has been sent.

This is useful for triggering an initial change notification after
subscribing to synchronize new receivers.

## tokio::mark_unchanged (function)

Marks the state as unchanged.

The current value will be considered seen by the receiver.

This is useful if you are not interested in the current value
visible in the receiver.

## tokio::max_blocking_threads (function)

Specifies the limit for additional threads spawned by the Runtime.

These threads are used for blocking operations like tasks spawned
through [`spawn_blocking`], this includes but is not limited to:
- [`fs`] operations
- dns resolution through [`ToSocketAddrs`]
- writing to [`Stdout`] or [`Stderr`]
- reading from [`Stdin`]

Unlike the [`worker_threads`], they are not always active and will exit
if left idle for too long. You can change this timeout duration with [`thread_keep_alive`].

It's recommended to not set this limit too low in order to avoid hanging on operations
requiring [`spawn_blocking`].

The default value is 512.

### tokio::max_blocking_threads (function) › Queue Behavior

When a blocking task is submitted, it will be inserted into a queue. If available, one of
the idle threads will be notified to run the task. Otherwise, if the threshold set by this
method has not been reached, a new thread will be spawned. If no idle thread is available
and no more threads are allowed to be spawned, the task will remain in the queue until one
of the busy threads pick it up. Note that since the queue does not apply any backpressure,
it could potentially grow unbounded.

### tokio::max_blocking_threads (function) › Panics

This will panic if `val` is not larger than `0`.

### tokio::max_blocking_threads (function) › Upgrading from 0.x

In old versions `max_threads` limited both blocking and worker threads, but the
current `max_blocking_threads` does not include async worker threads in the count.

[`spawn_blocking`]: fn@crate::task::spawn_blocking
[`fs`]: mod@crate::fs
[`ToSocketAddrs`]: trait@crate::net::ToSocketAddrs
[`Stdout`]: struct@crate::io::Stdout
[`Stdin`]: struct@crate::io::Stdin
[`Stderr`]: struct@crate::io::Stderr
[`worker_threads`]: Self::worker_threads
[`thread_keep_alive`]: Self::thread_keep_alive

## tokio::max_buckets (function)

Builds the log histogram, enforcing the max buckets requirement

## tokio::max_buf_size (function)

Get the maximum buffer size for the underlying [`AsyncRead`] / [`AsyncWrite`] operation.

## tokio::max_capacity (function)

Returns the maximum buffer capacity of the channel.

The maximum capacity is the buffer capacity initially specified when calling
[`channel`]. This is distinct from [`capacity`], which returns the *current*
available buffer capacity: as messages are sent and received, the
value returned by [`capacity`] will go up or down, whereas the value
returned by [`max_capacity`] will remain constant.

### tokio::max_capacity (function) › Examples

```
use tokio::sync::mpsc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, _rx) = mpsc::channel::<()>(5);

// both max capacity and capacity are the same at first
assert_eq!(tx.max_capacity(), 5);
assert_eq!(tx.capacity(), 5);

// Making a reservation doesn't change the max capacity.
let permit = tx.reserve().await.unwrap();
assert_eq!(tx.max_capacity(), 5);
// but drops the capacity by one
assert_eq!(tx.capacity(), 4);
# }
```

[`channel`]: channel
[`max_capacity`]: Sender::max_capacity
[`capacity`]: Sender::capacity

## tokio::max_capacity (function)

Returns the maximum buffer capacity of the channel.

The maximum capacity is the buffer capacity initially specified when calling
[`channel`]. This is distinct from [`capacity`], which returns the *current*
available buffer capacity: as messages are sent and received, the value
returned by [`capacity`] will go up or down, whereas the value
returned by [`max_capacity`] will remain constant.

### tokio::max_capacity (function) › Examples

```
use tokio::sync::mpsc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, rx) = mpsc::channel::<()>(5);

// both max capacity and capacity are the same at first
assert_eq!(rx.max_capacity(), 5);
assert_eq!(rx.capacity(), 5);

// Making a reservation doesn't change the max capacity.
let permit = tx.reserve().await.unwrap();
assert_eq!(rx.max_capacity(), 5);
// but drops the capacity by one
assert_eq!(rx.capacity(), 4);
# }
```
[`capacity`]: Receiver::capacity
[`max_capacity`]: Receiver::max_capacity

## tokio::max_error (function)

Set the precision for this histogram

This function determines the smallest value of `p` that would satisfy the requested precision
such that `2^-p` is less than `precision`. To set `p` directly, use
[`LogHistogramBuilder::precision_exact`].

Precision controls the size of the "bucket groups" (consecutive buckets with identical
ranges). When `p` is 0, each bucket will be twice the size of the previous bucket. To match
the behavior of the legacy log histogram implementation, use `builder.precision_exact(0)`.

The default value is 25% (2^-2)

The highest supported precision is `0.0977%` `(2^-10)`. Provided values
less than this will be truncated.

### tokio::max_error (function) › Panics
- `max_error` <= 0
- `max_error` >= 1

## tokio::max_instances (function)

The maximum number of instances that can be created for this pipe. The
first instance of the pipe can specify this value; the same number must
be specified for other instances of the pipe. Acceptable values are in
the range 1 through 254. The default value is unlimited.

This corresponds to specifying [`nMaxInstances`].

[`nMaxInstances`]: https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createnamedpipea

### tokio::max_instances (function) › Errors

The same numbers of `max_instances` have to be used by all servers. Any
additional servers trying to be built which uses a mismatching value
might error.

```
use std::io;
use tokio::net::windows::named_pipe::{ServerOptions, ClientOptions};
use windows_sys::Win32::Foundation::ERROR_PIPE_BUSY;

const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-max-instances";

# #[tokio::main] async fn main() -> io::Result<()> {
let mut server = ServerOptions::new();
server.max_instances(2);

let s1 = server.create(PIPE_NAME)?;
let c1 = ClientOptions::new().open(PIPE_NAME);

let s2 = server.create(PIPE_NAME)?;
let c2 = ClientOptions::new().open(PIPE_NAME);

// Too many servers!
let e = server.create(PIPE_NAME).unwrap_err();
assert_eq!(e.raw_os_error(), Some(ERROR_PIPE_BUSY as i32));

// Still too many servers even if we specify a higher value!
let e = server.max_instances(100).create(PIPE_NAME).unwrap_err();
assert_eq!(e.raw_os_error(), Some(ERROR_PIPE_BUSY as i32));
# Ok(()) }
```

### tokio::max_instances (function) › Panics

This function will panic if more than 254 instances are specified. If
you do not wish to set an instance limit, leave it unspecified.

```should_panic
use tokio::net::windows::named_pipe::ServerOptions;

# #[tokio::main] async fn main() -> std::io::Result<()> {
let builder = ServerOptions::new().max_instances(255);
# Ok(()) }
```

## tokio::max_instances (struct_field)

The maximum number of instances that can be created for this pipe.

## tokio::max_io_events_per_tick (function)

Enables the I/O driver and configures the max number of events to be
processed per tick.

### tokio::max_io_events_per_tick (function) › Examples

```
use tokio::runtime;

let rt = runtime::Builder::new_current_thread()
    .enable_io()
    .max_io_events_per_tick(1024)
    .build()
    .unwrap();
```

## tokio::max_value (function)

Sets the maximum value that can by this histogram without truncation

Values greater than this fall in the final bucket that stretches to `u64::MAX`.

### tokio::max_value (function) › Panics
The provided value is 0

## tokio::max_value (function)

The maximum value that can be stored before truncation in this histogram

## tokio::merge (function)

Merge two [`OwnedSemaphorePermit`] instances together, consuming `other`
without releasing the permits it holds.

Permits held by both `self` and `other` are released when `self` drops.

### tokio::merge (function) › Panics

This function panics if permits from different [`Semaphore`] instances
are merged.

### tokio::merge (function) › Examples

```
use std::sync::Arc;
use tokio::sync::Semaphore;

let sem = Arc::new(Semaphore::new(10));
let mut permit = sem.clone().try_acquire_owned().unwrap();

for _ in 0..9 {
    let _permit = sem.clone().try_acquire_owned().unwrap();
    // Merge individual permits into a single one.
    permit.merge(_permit)
}

assert_eq!(sem.available_permits(), 0);

// Release all permits in a single batch.
drop(permit);

assert_eq!(sem.available_permits(), 10);
```

## tokio::merge (function)

Merge two [`SemaphorePermit`] instances together, consuming `other`
without releasing the permits it holds.

Permits held by both `self` and `other` are released when `self` drops.

### tokio::merge (function) › Panics

This function panics if permits from different [`Semaphore`] instances
are merged.

### tokio::merge (function) › Examples

```
use std::sync::Arc;
use tokio::sync::Semaphore;

let sem = Arc::new(Semaphore::new(10));
let mut permit = sem.try_acquire().unwrap();

for _ in 0..9 {
    let _permit = sem.try_acquire().unwrap();
    // Merge individual permits into a single one.
    permit.merge(_permit)
}

assert_eq!(sem.available_permits(), 0);

// Release all permits in a single batch.
drop(permit);

assert_eq!(sem.available_permits(), 10);
```

## tokio::metadata (function)

Queries metadata about the underlying file.

### tokio::metadata (function) › Examples

```no_run
use tokio::fs::File;

# async fn dox() -> std::io::Result<()> {
let file = File::open("foo.txt").await?;
let metadata = file.metadata().await?;

println!("{:?}", metadata);
# Ok(())
# }
```

## tokio::metadata (function)

Returns the metadata for the file that this entry points at.

This function will not traverse symlinks if this entry points at a
symlink.

### tokio::metadata (function) › Platform-specific behavior

On Windows this function is cheap to call (no extra system calls
needed), but on Unix platforms this function is the equivalent of
calling `symlink_metadata` on the path.

### tokio::metadata (function) › Examples

```
use tokio::fs;

# async fn dox() -> std::io::Result<()> {
let mut entries = fs::read_dir(".").await?;

while let Some(entry) = entries.next_entry().await? {
    if let Ok(metadata) = entry.metadata().await {
        // Now let's show our entry's permissions!
        println!("{:?}: {:?}", entry.path(), metadata.permissions());
    } else {
        println!("Couldn't get file type for {:?}", entry.path());
    }
}
# Ok(())
# }
```

## tokio::metrics (function)

Returns a view that lets you get information about how the runtime
is performing.

## tokio::metrics (function)

Returns a view that lets you get information about how the runtime
is performing.

## tokio::metrics (function)

Returns a view that lets you get information about how the runtime
is performing.

## tokio::metrics_poll_count_histogram_buckets (function)

Sets the number of buckets for the histogram tracking the
distribution of task poll times.

The last bucket tracks all greater values that fall out of other
ranges. So, configuring the histogram using a linear scale,
resolution of 50ms, and 10 buckets, the 10th bucket will track task
polls that take more than 450ms to complete.

**Default:** 10

### tokio::metrics_poll_count_histogram_buckets (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime;

# #[allow(deprecated)]
let rt = runtime::Builder::new_multi_thread()
    .enable_metrics_poll_time_histogram()
    .metrics_poll_count_histogram_buckets(15)
    .build()
    .unwrap();
# }
```

## tokio::metrics_poll_count_histogram_resolution (function)

Sets the histogram resolution for tracking the distribution of task
poll times.

The resolution is the histogram's first bucket's range. When using a
linear histogram scale, each bucket will cover the same range. When
using a log scale, each bucket will cover a range twice as big as
the previous bucket. In the log case, the resolution represents the
smallest bucket range.

Note that, when using log scale, the resolution is rounded up to the
nearest power of 2 in nanoseconds.

**Default:** 100 microseconds.

### tokio::metrics_poll_count_histogram_resolution (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime;
use std::time::Duration;

# #[allow(deprecated)]
let rt = runtime::Builder::new_multi_thread()
    .enable_metrics_poll_time_histogram()
    .metrics_poll_count_histogram_resolution(Duration::from_micros(100))
    .build()
    .unwrap();
# }
```

## tokio::metrics_poll_count_histogram_scale (function)

Sets the histogram scale for tracking the distribution of task poll
times.

Tracking the distribution of task poll times can be done using a
linear or log scale. When using linear scale, each histogram bucket
will represent the same range of poll times. When using log scale,
each histogram bucket will cover a range twice as big as the
previous bucket.

**Default:** linear scale.

### tokio::metrics_poll_count_histogram_scale (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime::{self, HistogramScale};

# #[allow(deprecated)]
let rt = runtime::Builder::new_multi_thread()
    .enable_metrics_poll_time_histogram()
    .metrics_poll_count_histogram_scale(HistogramScale::Log)
    .build()
    .unwrap();
# }
```

## tokio::metrics_poll_time_histogram_configuration (function)

Configure the histogram for tracking poll times

By default, a linear histogram with 10 buckets each 100 microseconds wide will be used.
This has an extremely low memory footprint, but may not provide enough granularity. For
better granularity with low memory usage, use [`LogHistogram`] instead.

### tokio::metrics_poll_time_histogram_configuration (function) › Examples
Configure a [`LogHistogram`] with [default configuration]:
```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime;
use tokio::runtime::{HistogramConfiguration, LogHistogram};

let rt = runtime::Builder::new_multi_thread()
    .enable_metrics_poll_time_histogram()
    .metrics_poll_time_histogram_configuration(
        HistogramConfiguration::log(LogHistogram::default())
    )
    .build()
    .unwrap();
# }
```

Configure a linear histogram with 100 buckets, each 10μs wide
```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime;
use std::time::Duration;
use tokio::runtime::HistogramConfiguration;

let rt = runtime::Builder::new_multi_thread()
    .enable_metrics_poll_time_histogram()
    .metrics_poll_time_histogram_configuration(
        HistogramConfiguration::linear(Duration::from_micros(10), 100)
    )
    .build()
    .unwrap();
# }
```

Configure a [`LogHistogram`] with the following settings:
- Measure times from 100ns to 120s
- Max error of 0.1
- No more than 1024 buckets
```
# #[cfg(not(target_family = "wasm"))]
# {
use std::time::Duration;
use tokio::runtime;
use tokio::runtime::{HistogramConfiguration, LogHistogram};

let rt = runtime::Builder::new_multi_thread()
    .enable_metrics_poll_time_histogram()
    .metrics_poll_time_histogram_configuration(
        HistogramConfiguration::log(LogHistogram::builder()
            .max_value(Duration::from_secs(120))
            .min_value(Duration::from_nanos(100))
            .max_error(0.1)
            .max_buckets(1024)
            .expect("configuration uses 488 buckets")
        )
    )
    .build()
    .unwrap();
# }
```

When migrating from the legacy histogram ([`HistogramScale::Log`]) and wanting
to match the previous behavior, use `precision_exact(0)`. This creates a histogram
where each bucket is twice the size of the previous bucket.
```rust
use std::time::Duration;
use tokio::runtime::{HistogramConfiguration, LogHistogram};
let rt = tokio::runtime::Builder::new_current_thread()
    .enable_all()
    .enable_metrics_poll_time_histogram()
    .metrics_poll_time_histogram_configuration(HistogramConfiguration::log(
        LogHistogram::builder()
            .min_value(Duration::from_micros(20))
            .max_value(Duration::from_millis(4))
            // Set `precision_exact` to `0` to match `HistogramScale::Log`
            .precision_exact(0)
            .max_buckets(10)
            .unwrap(),
    ))
    .build()
    .unwrap();
```

[`LogHistogram`]: crate::runtime::LogHistogram
[default configuration]: crate::runtime::LogHistogramBuilder
[`HistogramScale::Log`]: crate::runtime::HistogramScale::Log

## tokio::metrics_schedule_latency_histogram_configuration (function)

Configure the histogram for tracking task schedule latencies.

Tracking of task schedule latencies must be enabled with
[`enable_metrics_schedule_latency_histogram()`] for this function
to have any effect.

By default, a linear histogram with 10 buckets each 100 microseconds wide will be used.
This has an extremely low memory footprint, but may not provide enough granularity. For
better granularity with low memory usage, use [`LogHistogram`] instead.

### tokio::metrics_schedule_latency_histogram_configuration (function) › Examples
Configure a [`LogHistogram`] with [default configuration]:
```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime;
use tokio::runtime::{HistogramConfiguration, LogHistogram};

let rt = runtime::Builder::new_multi_thread()
    .enable_metrics_schedule_latency_histogram()
    .metrics_schedule_latency_histogram_configuration(
        HistogramConfiguration::log(LogHistogram::default())
    )
    .build()
    .unwrap();
# }
```

Configure a linear histogram with 100 buckets, each 10μs wide
```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime;
use std::time::Duration;
use tokio::runtime::HistogramConfiguration;

let rt = runtime::Builder::new_multi_thread()
    .enable_metrics_schedule_latency_histogram()
    .metrics_schedule_latency_histogram_configuration(
        HistogramConfiguration::linear(Duration::from_micros(10), 100)
    )
    .build()
    .unwrap();
# }
```

Configure a [`LogHistogram`] with the following settings:
- Measure times from 100ns to 120s
- Max error of 0.1
- No more than 1024 buckets
```
# #[cfg(not(target_family = "wasm"))]
# {
use std::time::Duration;
use tokio::runtime;
use tokio::runtime::{HistogramConfiguration, LogHistogram};

let rt = runtime::Builder::new_multi_thread()
    .enable_metrics_schedule_latency_histogram()
    .metrics_schedule_latency_histogram_configuration(
        HistogramConfiguration::log(LogHistogram::builder()
            .max_value(Duration::from_secs(120))
            .min_value(Duration::from_nanos(100))
            .max_error(0.1)
            .max_buckets(1024)
            .expect("configuration uses 488 buckets")
        )
    )
    .build()
    .unwrap();
# }
```

[`LogHistogram`]: crate::runtime::LogHistogram
[`enable_metrics_schedule_latency_histogram()`]: Builder::enable_metrics_schedule_latency_histogram

## tokio::min_value (function)

Sets the minimum duration that can be accurately stored by this histogram.

This sets the resolution. The first bucket will be no larger than
the provided duration. Setting this value will reduce the number of required buckets,
sometimes quite significantly.

## tokio::missed_tick_behavior (function)

Returns the [`MissedTickBehavior`] strategy currently being used.

## tokio::mode (function)

Sets the mode bits that a new file will be created with.

If a new file is created as part of an `OpenOptions::open` call then this
specified `mode` will be used as the permission bits for the new file.
If no `mode` is set, the default of `0o666` will be used.
The operating system masks out bits with the system's `umask`, to produce
the final permissions.

### tokio::mode (function) › Examples

```no_run
use tokio::fs::OpenOptions;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let mut options = OpenOptions::new();
    options.mode(0o644); // Give read/write for owner and read for others.
    let file = options.open("foo.txt").await?;

    Ok(())
}
```

## tokio::mode (function)

Sets the mode to create new directories with.

This option defaults to 0o777.

### tokio::mode (function) › Examples


```no_run
use tokio::fs::DirBuilder;

let mut builder = DirBuilder::new();
builder.mode(0o775);
```

## tokio::mode (struct_field)

Indicates the mode of a named pipe.

## tokio::multicast_loop_v4 (function)

Gets the value of the `IP_MULTICAST_LOOP` option for this socket.

For more information about this option, see [`set_multicast_loop_v4`].

[`set_multicast_loop_v4`]: method@Self::set_multicast_loop_v4

## tokio::multicast_loop_v6 (function)

Gets the value of the `IPV6_MULTICAST_LOOP` option for this socket.

For more information about this option, see [`set_multicast_loop_v6`].

[`set_multicast_loop_v6`]: method@Self::set_multicast_loop_v6

## tokio::multicast_ttl_v4 (function)

Gets the value of the `IP_MULTICAST_TTL` option for this socket.

For more information about this option, see [`set_multicast_ttl_v4`].

[`set_multicast_ttl_v4`]: method@Self::set_multicast_ttl_v4

## tokio::mutex (function)

Returns a reference to the original `Arc<Mutex>`.

```
use std::sync::Arc;
use tokio::sync::{Mutex, OwnedMutexGuard};

async fn unlock_and_relock(guard: OwnedMutexGuard<u32>) -> OwnedMutexGuard<u32> {
    println!("1. contains: {:?}", *guard);
    let mutex: Arc<Mutex<u32>> = OwnedMutexGuard::mutex(&guard).clone();
    drop(guard);
    let guard = mutex.lock_owned().await;
    println!("2. contains: {:?}", *guard);
    guard
}
#
# #[tokio::main(flavor = "current_thread")]
# async fn main() {
#     let mutex = Arc::new(Mutex::new(0u32));
#     let guard = mutex.lock_owned().await;
#     unlock_and_relock(guard).await;
# }
```

## tokio::mutex (function)

Returns a reference to the original `Mutex`.

```
use tokio::sync::{Mutex, MutexGuard};

async fn unlock_and_relock<'l>(guard: MutexGuard<'l, u32>) -> MutexGuard<'l, u32> {
    println!("1. contains: {:?}", *guard);
    let mutex = MutexGuard::mutex(&guard);
    drop(guard);
    let guard = mutex.lock().await;
    println!("2. contains: {:?}", *guard);
    guard
}
#
# #[tokio::main(flavor = "current_thread")]
# async fn main() {
#     let mutex = Mutex::new(0u32);
#     let guard = mutex.lock().await;
#     let _guard = unlock_and_relock(guard).await;
# }
```

## tokio::name (function)

Assigns a name to the task which will be spawned.

## tokio::name (function)

Assigns a name to the task which will be spawned.

## tokio::name (function)

Returns the name of the current `Runtime`.

### tokio::name (function) › Examples

```
use tokio::runtime::Handle;

#[tokio::main(flavor = "current_thread", name = "my-runtime")]
async fn main() {
  println!("Current runtime name: {}", Handle::current().name().unwrap());
}
```

## tokio::name (function)

Sets the name of the runtime.

### tokio::name (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
# use tokio::runtime;

# pub fn main() {
let rt = runtime::Builder::new_multi_thread()
    .name("my-runtime")
    .build();
# }
# }
```
### tokio::name (function) › Panics

This function will panic if an empty value is passed as an argument.

## tokio::name_demangled (function)

Return the demangled name of the symbol.

## tokio::name_raw (function)

Return the raw name of the symbol.

## tokio::net::addr::ToSocketAddrs (trait)

Converts or resolves without blocking to one or more `SocketAddr` values.

### tokio::net::addr::ToSocketAddrs (trait) › DNS

Implementations of `ToSocketAddrs` for string types require a DNS lookup.

### tokio::net::addr::ToSocketAddrs (trait) › Calling

Currently, this trait is only used as an argument to Tokio functions that
need to reference a target socket address. To perform a `SocketAddr`
conversion directly, use [`lookup_host()`](super::lookup_host()).

This trait is sealed and is intended to be opaque. The details of the trait
will change. Stabilization is pending enhancements to the Rust language.

## tokio::net::lookup_host::lookup_host (function)

Performs a DNS resolution.

The returned iterator may not actually yield any values depending on the
outcome of any resolution performed.

This API is not intended to cover all DNS use cases. Anything beyond the
basic use case should be done with a specialized library.

### tokio::net::lookup_host::lookup_host (function) › Examples

To resolve a DNS entry:

```no_run
use tokio::net;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    for addr in net::lookup_host("localhost:3000").await? {
        println!("socket address is {}", addr);
    }

    Ok(())
}
```

## tokio::net::tcp::listener::TcpListener (struct)

A TCP socket server, listening for connections.

You can accept a new connection by using the [`accept`](`TcpListener::accept`)
method.

A `TcpListener` can be turned into a `Stream` with [`TcpListenerStream`].

The socket will be closed when the value is dropped.

[`TcpListenerStream`]: https://docs.rs/tokio-stream/0.1/tokio_stream/wrappers/struct.TcpListenerStream.html

### tokio::net::tcp::listener::TcpListener (struct) › Errors

Note that accepting a connection can lead to various errors and not all
of them are necessarily fatal ‒ for example having too many open file
descriptors or the other side closing the connection while it waits in
an accept queue. These would terminate the stream if not handled in any
way.

### tokio::net::tcp::listener::TcpListener (struct) › Examples

Using `accept`:
```no_run
use tokio::net::TcpListener;

use std::io;

async fn process_socket<T>(socket: T) {
    # drop(socket);
    // do work with socket here
}

#[tokio::main]
async fn main() -> io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:8080").await?;

    loop {
        let (socket, _) = listener.accept().await?;
        process_socket(socket).await;
    }
}
```

## tokio::net::tcp::socket::TcpSocket (struct)

A TCP socket that has not yet been converted to a `TcpStream` or
`TcpListener`.

`TcpSocket` wraps an operating system socket and enables the caller to
configure the socket before establishing a TCP connection or accepting
inbound connections. The caller is able to set socket option and explicitly
bind the socket with a socket address.

The underlying socket is closed when the `TcpSocket` value is dropped.

`TcpSocket` should only be used directly if the default configuration used
by `TcpStream::connect` and `TcpListener::bind` does not meet the required
use case.

Calling `TcpStream::connect("127.0.0.1:8080")` is equivalent to:

```no_run
use tokio::net::TcpSocket;

use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let addr = "127.0.0.1:8080".parse().unwrap();

    let socket = TcpSocket::new_v4()?;
    let stream = socket.connect(addr).await?;
# drop(stream);

    Ok(())
}
```

Calling `TcpListener::bind("127.0.0.1:8080")` is equivalent to:

```no_run
use tokio::net::TcpSocket;

use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let addr = "127.0.0.1:8080".parse().unwrap();

    let socket = TcpSocket::new_v4()?;
    // On platforms with Berkeley-derived sockets, this allows to quickly
    // rebind a socket, without needing to wait for the OS to clean up the
    // previous one.
    //
    // On Windows, this allows rebinding sockets which are actively in use,
    // which allows "socket hijacking", so we explicitly don't set it here.
    // https://docs.microsoft.com/en-us/windows/win32/winsock/using-so-reuseaddr-and-so-exclusiveaddruse
    socket.set_reuseaddr(true)?;
    socket.bind(addr)?;

    // Note: the actual backlog used by `TcpListener::bind` is platform-dependent,
    // as Tokio relies on Mio's default backlog value configuration. The `1024` here is only
    // illustrative and does not reflect the real value used.
    let listener = socket.listen(1024)?;
# drop(listener);

    Ok(())
}
```

Setting socket options not explicitly provided by `TcpSocket` may be done by
accessing the `RawFd`/`RawSocket` using [`AsRawFd`]/[`AsRawSocket`] and
setting the option with a crate like [`socket2`].

[`RawFd`]: https://doc.rust-lang.org/std/os/fd/type.RawFd.html
[`RawSocket`]: https://doc.rust-lang.org/std/os/windows/io/type.RawSocket.html
[`AsRawFd`]: https://doc.rust-lang.org/std/os/fd/trait.AsRawFd.html
[`AsRawSocket`]: https://doc.rust-lang.org/std/os/windows/io/trait.AsRawSocket.html
[`socket2`]: https://docs.rs/socket2/

## tokio::net::tcp::split::ReadHalf (struct)

Borrowed read half of a [`TcpStream`], created by [`split`].

Reading from a `ReadHalf` is usually done using the convenience methods found on the
[`AsyncReadExt`] trait.

[`TcpStream`]: TcpStream
[`split`]: TcpStream::split()
[`AsyncReadExt`]: trait@crate::io::AsyncReadExt

## tokio::net::tcp::split::WriteHalf (struct)

Borrowed write half of a [`TcpStream`], created by [`split`].

Note that in the [`AsyncWrite`] implementation of this type, [`poll_shutdown`] will
shut down the TCP stream in the write direction.

Writing to an `WriteHalf` is usually done using the convenience methods found
on the [`AsyncWriteExt`] trait.

[`TcpStream`]: TcpStream
[`split`]: TcpStream::split()
[`AsyncWrite`]: trait@crate::io::AsyncWrite
[`poll_shutdown`]: fn@crate::io::AsyncWrite::poll_shutdown
[`AsyncWriteExt`]: trait@crate::io::AsyncWriteExt

## tokio::net::tcp::split_owned::OwnedReadHalf (struct)

Owned read half of a [`TcpStream`], created by [`into_split`].

Reading from an `OwnedReadHalf` is usually done using the convenience methods found
on the [`AsyncReadExt`] trait.

[`TcpStream`]: TcpStream
[`into_split`]: TcpStream::into_split()
[`AsyncReadExt`]: trait@crate::io::AsyncReadExt

## tokio::net::tcp::split_owned::OwnedWriteHalf (struct)

Owned write half of a [`TcpStream`], created by [`into_split`].

Note that in the [`AsyncWrite`] implementation of this type, [`poll_shutdown`] will
shut down the TCP stream in the write direction.  Dropping the write half
will also shut down the write half of the TCP stream.

Writing to an `OwnedWriteHalf` is usually done using the convenience methods found
on the [`AsyncWriteExt`] trait.

[`TcpStream`]: TcpStream
[`into_split`]: TcpStream::into_split()
[`AsyncWrite`]: trait@crate::io::AsyncWrite
[`poll_shutdown`]: fn@crate::io::AsyncWrite::poll_shutdown
[`AsyncWriteExt`]: trait@crate::io::AsyncWriteExt

## tokio::net::tcp::split_owned::ReuniteError (struct)

Error indicating that two halves were not from the same socket, and thus could
not be reunited.

## tokio::net::tcp::stream::TcpStream (struct)

A TCP stream between a local and a remote socket.

A TCP stream can either be created by connecting to an endpoint, via the
[`connect`] method, or by [accepting] a connection from a [listener]. A
TCP stream can also be created via the [`TcpSocket`] type.

Reading and writing to a `TcpStream` is usually done using the
convenience methods found on the [`AsyncReadExt`] and [`AsyncWriteExt`]
traits.

[`connect`]: method@TcpStream::connect
[accepting]: method@crate::net::TcpListener::accept
[listener]: struct@crate::net::TcpListener
[`TcpSocket`]: struct@crate::net::TcpSocket
[`AsyncReadExt`]: trait@crate::io::AsyncReadExt
[`AsyncWriteExt`]: trait@crate::io::AsyncWriteExt

### tokio::net::tcp::stream::TcpStream (struct) › Examples

```no_run
use tokio::net::TcpStream;
use tokio::io::AsyncWriteExt;
use std::error::Error;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // Connect to a peer
    let mut stream = TcpStream::connect("127.0.0.1:8080").await?;

    // Write some data.
    stream.write_all(b"hello world!").await?;

    Ok(())
}
```

The [`write_all`] method is defined on the [`AsyncWriteExt`] trait.

[`write_all`]: fn@crate::io::AsyncWriteExt::write_all
[`AsyncWriteExt`]: trait@crate::io::AsyncWriteExt

To shut down the stream in the write direction, you can call the
[`shutdown()`] method. This will cause the other peer to receive a read of
length 0, indicating that no more data will be sent. This only closes
the stream in one direction.

[`shutdown()`]: fn@crate::io::AsyncWriteExt::shutdown

## tokio::net::udp::UdpSocket (struct)

A UDP socket.

UDP is "connectionless", unlike TCP. Meaning, regardless of what address you've bound to, a `UdpSocket`
is free to communicate with many different remotes. In tokio there are basically two main ways to use `UdpSocket`:

* one to many: [`bind`](`UdpSocket::bind`) and use [`send_to`](`UdpSocket::send_to`)
  and [`recv_from`](`UdpSocket::recv_from`) to communicate with many different addresses
* one to one: [`connect`](`UdpSocket::connect`) and associate with a single address, using [`send`](`UdpSocket::send`)
  and [`recv`](`UdpSocket::recv`) to communicate only with that remote address

This type does not provide a `split` method, because this functionality
can be achieved by instead wrapping the socket in an [`Arc`]. Note that
you do not need a `Mutex` to share the `UdpSocket` — an `Arc<UdpSocket>`
is enough. This is because all of the methods take `&self` instead of
`&mut self`. Once you have wrapped it in an `Arc`, you can call
`.clone()` on the `Arc<UdpSocket>` to get multiple shared handles to the
same socket. An example of such usage can be found further down.

[`Arc`]: std::sync::Arc

### tokio::net::udp::UdpSocket (struct) › Streams

If you need to listen over UDP and produce a [`Stream`], you can look
at [`UdpFramed`].

[`UdpFramed`]: https://docs.rs/tokio-util/latest/tokio_util/udp/struct.UdpFramed.html
[`Stream`]: https://docs.rs/futures/0.3/futures/stream/trait.Stream.html

### tokio::net::udp::UdpSocket (struct) › Example: one to many (bind)

Using `bind` we can create a simple echo server that sends and recv's with many different clients:
```no_run
use tokio::net::UdpSocket;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let sock = UdpSocket::bind("0.0.0.0:8080").await?;
    let mut buf = [0; 1024];
    loop {
        let (len, addr) = sock.recv_from(&mut buf).await?;
        println!("{:?} bytes received from {:?}", len, addr);

        let len = sock.send_to(&buf[..len], addr).await?;
        println!("{:?} bytes sent", len);
    }
}
```

### tokio::net::udp::UdpSocket (struct) › Example: one to one (connect)

Or using `connect` we can echo with a single remote address using `send` and `recv`:
```no_run
use tokio::net::UdpSocket;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let sock = UdpSocket::bind("0.0.0.0:8080").await?;

    let remote_addr = "127.0.0.1:59611";
    sock.connect(remote_addr).await?;
    let mut buf = [0; 1024];
    loop {
        let len = sock.recv(&mut buf).await?;
        println!("{:?} bytes received from {:?}", len, remote_addr);

        let len = sock.send(&buf[..len]).await?;
        println!("{:?} bytes sent", len);
    }
}
```

### tokio::net::udp::UdpSocket (struct) › Example: Splitting with `Arc`

Because `send_to` and `recv_from` take `&self`. It's perfectly alright
to use an `Arc<UdpSocket>` and share the references to multiple tasks.
Here is a similar "echo" example that supports concurrent
sending/receiving:

```no_run
use tokio::{net::UdpSocket, sync::mpsc};
use std::{io, net::SocketAddr, sync::Arc};

#[tokio::main]
async fn main() -> io::Result<()> {
    let sock = UdpSocket::bind("0.0.0.0:8080".parse::<SocketAddr>().unwrap()).await?;
    let r = Arc::new(sock);
    let s = r.clone();
    let (tx, mut rx) = mpsc::channel::<(Vec<u8>, SocketAddr)>(1_000);

    tokio::spawn(async move {
        while let Some((bytes, addr)) = rx.recv().await {
            let len = s.send_to(&bytes, &addr).await.unwrap();
            println!("{:?} bytes sent", len);
        }
    });

    let mut buf = [0; 1024];
    loop {
        let (len, addr) = r.recv_from(&mut buf).await?;
        println!("{:?} bytes received from {:?}", len, addr);
        tx.send((buf[..len].to_vec(), addr)).await.unwrap();
    }
}
```

## tokio::net::unix::gid_t (type_alias)

A type representing group ID.

## tokio::net::unix::listener::UnixListener (struct)

A Unix socket which can accept connections from other Unix sockets.

You can accept a new connection by using the [`accept`](`UnixListener::accept`) method.

A `UnixListener` can be turned into a `Stream` with [`UnixListenerStream`].

[`UnixListenerStream`]: https://docs.rs/tokio-stream/0.1/tokio_stream/wrappers/struct.UnixListenerStream.html

### tokio::net::unix::listener::UnixListener (struct) › Errors

Note that accepting a connection can lead to various errors and not all
of them are necessarily fatal ‒ for example having too many open file
descriptors or the other side closing the connection while it waits in
an accept queue. These would terminate the stream if not handled in any
way.

### tokio::net::unix::listener::UnixListener (struct) › Examples

```no_run
use tokio::net::UnixListener;

#[tokio::main]
async fn main() {
    let listener = UnixListener::bind("/path/to/the/socket").unwrap();
    loop {
        match listener.accept().await {
            Ok((stream, _addr)) => {
                println!("new client!");
            }
            Err(e) => { /* connection failed */ }
        }
    }
}
```

## tokio::net::unix::pid_t (type_alias)

A type representing process and process group IDs.

## tokio::net::unix::pipe::OpenOptions (struct)

Options and flags which can be used to configure how a FIFO file is opened.

This builder allows configuring how to create a pipe end from a FIFO file.
Generally speaking, when using `OpenOptions`, you'll first call [`new`],
then chain calls to methods to set each option, then call either
[`open_receiver`] or [`open_sender`], passing the path of the FIFO file you
are trying to open. This will give you a [`io::Result`] with a pipe end
inside that you can further operate on.

[`new`]: OpenOptions::new
[`open_receiver`]: OpenOptions::open_receiver
[`open_sender`]: OpenOptions::open_sender

### tokio::net::unix::pipe::OpenOptions (struct) › Examples

Opening a pair of pipe ends from a FIFO file:

```no_run
use tokio::net::unix::pipe;
# use std::error::Error;

const FIFO_NAME: &str = "path/to/a/fifo";

# async fn dox() -> Result<(), Box<dyn Error>> {
let rx = pipe::OpenOptions::new().open_receiver(FIFO_NAME)?;
let tx = pipe::OpenOptions::new().open_sender(FIFO_NAME)?;
# Ok(())
# }
```

Opening a [`Sender`] on Linux when you are sure the file is a FIFO:

```ignore
use tokio::net::unix::pipe;
use nix::{unistd::mkfifo, sys::stat::Mode};
# use std::error::Error;

// Our program has exclusive access to this path.
const FIFO_NAME: &str = "path/to/a/new/fifo";

# async fn dox() -> Result<(), Box<dyn Error>> {
mkfifo(FIFO_NAME, Mode::S_IRWXU)?;
let tx = pipe::OpenOptions::new()
    .read_write(true)
    .unchecked(true)
    .open_sender(FIFO_NAME)?;
# Ok(())
# }
```

## tokio::net::unix::pipe::Receiver (struct)

Reading end of a Unix pipe.

It can be constructed from a FIFO file with [`OpenOptions::open_receiver`].

### tokio::net::unix::pipe::Receiver (struct) › Examples

Receiving messages from a named pipe in a loop:

```no_run
use tokio::net::unix::pipe;
use tokio::io::{self, AsyncReadExt};

const FIFO_NAME: &str = "path/to/a/fifo";

# async fn dox() -> Result<(), Box<dyn std::error::Error>> {
let mut rx = pipe::OpenOptions::new().open_receiver(FIFO_NAME)?;
loop {
    let mut msg = vec![0; 256];
    match rx.read_exact(&mut msg).await {
        Ok(_) => {
            /* handle the message */
        }
        Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => {
            // Writing end has been closed, we should reopen the pipe.
            rx = pipe::OpenOptions::new().open_receiver(FIFO_NAME)?;
        }
        Err(e) => return Err(e.into()),
    }
}
# }
```

On Linux, you can use a `Receiver` in read-write access mode to implement
resilient reading from a named pipe. Unlike `Receiver` opened in read-only
mode, read from a pipe in read-write mode will not fail with `UnexpectedEof`
when the writing end is closed. This way, a `Receiver` can asynchronously
wait for the next writer to open the pipe.

You should not use functions waiting for EOF such as [`read_to_end`] with
a `Receiver` in read-write access mode, since it **may wait forever**.
`Receiver` in this mode also holds an open writing end, which prevents
receiving EOF.

To set the read-write access mode you can use `OpenOptions::read_write`.
Note that using read-write access mode with FIFO files is not defined by
the POSIX standard and it is only guaranteed to work on Linux.

```ignore
use tokio::net::unix::pipe;
use tokio::io::AsyncReadExt;
# use std::error::Error;

const FIFO_NAME: &str = "path/to/a/fifo";

# async fn dox() -> Result<(), Box<dyn Error>> {
let mut rx = pipe::OpenOptions::new()
    .read_write(true)
    .open_receiver(FIFO_NAME)?;
loop {
    let mut msg = vec![0; 256];
    rx.read_exact(&mut msg).await?;
    /* handle the message */
}
# }
```

[`read_to_end`]: crate::io::AsyncReadExt::read_to_end

## tokio::net::unix::pipe::Sender (struct)

Writing end of a Unix pipe.

It can be constructed from a FIFO file with [`OpenOptions::open_sender`].

Opening a named pipe for writing involves a few steps.
Call to [`OpenOptions::open_sender`] might fail with an error indicating
different things:

* [`io::ErrorKind::NotFound`] - There is no file at the specified path.
* [`io::ErrorKind::InvalidInput`] - The file exists, but it is not a FIFO.
* [`ENXIO`] - The file is a FIFO, but no process has it open for reading.
  Sleep for a while and try again.
* Other OS errors not specific to opening FIFO files.

Opening a `Sender` from a FIFO file should look like this:

```no_run
use tokio::net::unix::pipe;
use tokio::time::{self, Duration};

const FIFO_NAME: &str = "path/to/a/fifo";

# async fn dox() -> Result<(), Box<dyn std::error::Error>> {
// Wait for a reader to open the file.
let tx = loop {
    match pipe::OpenOptions::new().open_sender(FIFO_NAME) {
        Ok(tx) => break tx,
        Err(e) if e.raw_os_error() == Some(libc::ENXIO) => {},
        Err(e) => return Err(e.into()),
    }

    time::sleep(Duration::from_millis(50)).await;
};
# Ok(())
# }
```

On Linux, it is possible to create a `Sender` without waiting in a sleeping
loop. This is done by opening a named pipe in read-write access mode with
`OpenOptions::read_write`. This way, a `Sender` can at the same time hold
both a writing end and a reading end, and the latter allows to open a FIFO
without [`ENXIO`] error since the pipe is open for reading as well.

`Sender` cannot be used to read from a pipe, so in practice the read access
is only used when a FIFO is opened. However, using a `Sender` in read-write
mode **may lead to lost data**, because written data will be dropped by the
system as soon as all pipe ends are closed. To avoid lost data you have to
make sure that a reading end has been opened before dropping a `Sender`.

Note that using read-write access mode with FIFO files is not defined by
the POSIX standard and it is only guaranteed to work on Linux.

```ignore
use tokio::io::AsyncWriteExt;
use tokio::net::unix::pipe;

const FIFO_NAME: &str = "path/to/a/fifo";

# async fn dox() -> Result<(), Box<dyn std::error::Error>> {
let mut tx = pipe::OpenOptions::new()
    .read_write(true)
    .open_sender(FIFO_NAME)?;

// Asynchronously write to the pipe before a reader.
tx.write_all(b"hello world").await?;
# Ok(())
# }
```

[`ENXIO`]: https://docs.rs/libc/latest/libc/constant.ENXIO.html

## tokio::net::unix::pipe::pipe (function)

Creates a new anonymous Unix pipe.

This function will open a new pipe and associate both pipe ends with the default
event loop.

If you need to create a pipe for communication with a spawned process, you can
use [`Stdio::piped()`] instead.

[`Stdio::piped()`]: std::process::Stdio::piped

### tokio::net::unix::pipe::pipe (function) › Errors

If creating a pipe fails, this function will return with the related OS error.

### tokio::net::unix::pipe::pipe (function) › Examples

Create a pipe and pass the writing end to a spawned process.

```no_run
use tokio::net::unix::pipe;
use tokio::process::Command;
# use tokio::io::AsyncReadExt;
# use std::error::Error;

# async fn dox() -> Result<(), Box<dyn Error>> {
let (tx, mut rx) = pipe::pipe()?;
let mut buffer = String::new();

let status = Command::new("echo")
    .arg("Hello, world!")
    .stdout(tx.into_blocking_fd()?)
    .status();
rx.read_to_string(&mut buffer).await?;

assert!(status.await?.success());
assert_eq!(buffer, "Hello, world!\n");
# Ok(())
# }
```

### tokio::net::unix::pipe::pipe (function) › Panics

This function panics if it is not called from within a runtime with
IO enabled.

The runtime is usually set implicitly when this function is called
from a future driven by a tokio runtime, otherwise runtime can be set
explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.

## tokio::net::unix::socket::UnixSocket (struct)

A Unix socket that has not yet been converted to a [`UnixStream`], [`UnixDatagram`], or
[`UnixListener`].

`UnixSocket` wraps an operating system socket and enables the caller to
configure the socket before establishing a connection or accepting
inbound connections. The caller is able to set socket option and explicitly
bind the socket with a socket address.

The underlying socket is closed when the `UnixSocket` value is dropped.

`UnixSocket` should only be used directly if the default configuration used
by [`UnixStream::connect`], [`UnixDatagram::bind`], and [`UnixListener::bind`]
does not meet the required use case.

Calling `UnixStream::connect(path)` effectively performs the same function as:

```no_run
use tokio::net::UnixSocket;
use std::error::Error;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("bind_path");
    let socket = UnixSocket::new_stream()?;

    let stream = socket.connect(path).await?;

    Ok(())
}
```

Calling `UnixDatagram::bind(path)` effectively performs the same function as:

```no_run
use tokio::net::UnixSocket;
use std::error::Error;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("bind_path");
    let socket = UnixSocket::new_datagram()?;
    socket.bind(path)?;

    let datagram = socket.datagram()?;

    Ok(())
}
```

Calling `UnixListener::bind(path)` effectively performs the same function as:

```no_run
use tokio::net::UnixSocket;
use std::error::Error;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("bind_path");
    let socket = UnixSocket::new_stream()?;
    socket.bind(path)?;

    let listener = socket.listen(1024)?;

    Ok(())
}
```

Setting socket options not explicitly provided by `UnixSocket` may be done by
accessing the [`RawFd`]/[`RawSocket`] using [`AsRawFd`]/[`AsRawSocket`] and
setting the option with a crate like [`socket2`].

[`RawFd`]: std::os::fd::RawFd
[`RawSocket`]: https://doc.rust-lang.org/std/os/windows/io/type.RawSocket.html
[`AsRawFd`]: std::os::fd::AsRawFd
[`AsRawSocket`]: https://doc.rust-lang.org/std/os/windows/io/trait.AsRawSocket.html
[`socket2`]: https://docs.rs/socket2/

## tokio::net::unix::socketaddr::SocketAddr (struct)

An address associated with a Tokio Unix socket.

This type is a thin wrapper around [`std::os::unix::net::SocketAddr`]. You
can convert to and from the standard library `SocketAddr` type using the
[`From`] trait.

## tokio::net::unix::split::ReadHalf (struct)

Borrowed read half of a [`UnixStream`], created by [`split`].

Reading from a `ReadHalf` is usually done using the convenience methods found on the
[`AsyncReadExt`] trait.

[`UnixStream`]: UnixStream
[`split`]: UnixStream::split()
[`AsyncReadExt`]: trait@crate::io::AsyncReadExt

## tokio::net::unix::split::WriteHalf (struct)

Borrowed write half of a [`UnixStream`], created by [`split`].

Note that in the [`AsyncWrite`] implementation of this type, [`poll_shutdown`] will
shut down the [`UnixStream`] stream in the write direction.

Writing to an `WriteHalf` is usually done using the convenience methods found
on the [`AsyncWriteExt`] trait.

[`UnixStream`]: UnixStream
[`split`]: UnixStream::split()
[`AsyncWrite`]: trait@crate::io::AsyncWrite
[`poll_shutdown`]: fn@crate::io::AsyncWrite::poll_shutdown
[`AsyncWriteExt`]: trait@crate::io::AsyncWriteExt

## tokio::net::unix::split_owned::OwnedReadHalf (struct)

Owned read half of a [`UnixStream`], created by [`into_split`].

Reading from an `OwnedReadHalf` is usually done using the convenience methods found
on the [`AsyncReadExt`] trait.

[`UnixStream`]: crate::net::UnixStream
[`into_split`]: crate::net::UnixStream::into_split()
[`AsyncReadExt`]: trait@crate::io::AsyncReadExt

## tokio::net::unix::split_owned::OwnedWriteHalf (struct)

Owned write half of a [`UnixStream`], created by [`into_split`].

Note that in the [`AsyncWrite`] implementation of this type,
[`poll_shutdown`] will shut down the stream in the write direction.
Dropping the write half will also shut down the write half of the stream.

Writing to an `OwnedWriteHalf` is usually done using the convenience methods
found on the [`AsyncWriteExt`] trait.

[`UnixStream`]: crate::net::UnixStream
[`into_split`]: crate::net::UnixStream::into_split()
[`AsyncWrite`]: trait@crate::io::AsyncWrite
[`poll_shutdown`]: fn@crate::io::AsyncWrite::poll_shutdown
[`AsyncWriteExt`]: trait@crate::io::AsyncWriteExt

## tokio::net::unix::split_owned::ReuniteError (struct)

Error indicating that two halves were not from the same socket, and thus could
not be reunited.

## tokio::net::unix::stream::UnixStream (struct)

A structure representing a connected Unix socket.

This socket can be connected directly with [`UnixStream::connect`] or accepted
from a listener with [`UnixListener::accept`]. Additionally, a pair of
anonymous Unix sockets can be created with `UnixStream::pair`.

To shut down the stream in the write direction, you can call the
[`shutdown()`] method. This will cause the other peer to receive a read of
length 0, indicating that no more data will be sent. This only closes
the stream in one direction.

[`shutdown()`]: fn@crate::io::AsyncWriteExt::shutdown
[`UnixListener::accept`]: crate::net::UnixListener::accept

## tokio::net::unix::ucred::UCred (struct)

Credentials of a process.

## tokio::net::unix::uid_t (type_alias)

A type representing user ID.

## tokio::net::windows::named_pipe::ClientOptions (struct)

A builder suitable for building and interacting with named pipes from the
client side.

See [`ClientOptions::open`].

## tokio::net::windows::named_pipe::NamedPipeClient (struct)

A [Windows named pipe] client.

Constructed using [`ClientOptions::open`].

Connecting a client correctly involves a few steps. When connecting through
[`ClientOptions::open`], it might error indicating one of two things:

* [`std::io::ErrorKind::NotFound`] - There is no server available.
* [`ERROR_PIPE_BUSY`] - There is a server available, but it is busy. Sleep
  for a while and try again.

So a correctly implemented client looks like this:

```no_run
use std::time::Duration;
use tokio::net::windows::named_pipe::ClientOptions;
use tokio::time;
use windows_sys::Win32::Foundation::ERROR_PIPE_BUSY;

const PIPE_NAME: &str = r"\\.\pipe\named-pipe-idiomatic-client";

# #[tokio::main] async fn main() -> std::io::Result<()> {
let client = loop {
    match ClientOptions::new().open(PIPE_NAME) {
        Ok(client) => break client,
        Err(e) if e.raw_os_error() == Some(ERROR_PIPE_BUSY as i32) => (),
        Err(e) => return Err(e),
    }

    time::sleep(Duration::from_millis(50)).await;
};

/* use the connected client */
# Ok(()) }
```

[`ERROR_PIPE_BUSY`]: https://docs.rs/windows-sys/latest/windows_sys/Win32/Foundation/constant.ERROR_PIPE_BUSY.html
[Windows named pipe]: https://docs.microsoft.com/en-us/windows/win32/ipc/named-pipes

## tokio::net::windows::named_pipe::NamedPipeServer (struct)

A [Windows named pipe] server.

Accepting client connections involves creating a server with
[`ServerOptions::create`] and waiting for clients to connect using
[`NamedPipeServer::connect`].

To avoid having clients sporadically fail with
[`std::io::ErrorKind::NotFound`] when they connect to a server, we must
ensure that at least one server instance is available at all times. This
means that the typical listen loop for a server is a bit involved, because
we have to ensure that we never drop a server accidentally while a client
might connect.

So a correctly implemented server looks like this:

```no_run
use std::io;
use tokio::net::windows::named_pipe::ServerOptions;

const PIPE_NAME: &str = r"\\.\pipe\named-pipe-idiomatic-server";

# #[tokio::main] async fn main() -> std::io::Result<()> {
// The first server needs to be constructed early so that clients can
// be correctly connected. Otherwise calling .wait will cause the client to
// error.
//
// Here we also make use of `first_pipe_instance`, which will ensure that
// there are no other servers up and running already.
let mut server = ServerOptions::new()
    .first_pipe_instance(true)
    .create(PIPE_NAME)?;

// Spawn the server loop.
let server = tokio::spawn(async move {
    loop {
        // Wait for a client to connect.
        server.connect().await?;
        let connected_client = server;

        // Construct the next server to be connected before sending the one
        // we already have of onto a task. This ensures that the server
        // isn't closed (after it's done in the task) before a new one is
        // available. Otherwise the client might error with
        // `io::ErrorKind::NotFound`.
        server = ServerOptions::new().create(PIPE_NAME)?;

        let client = tokio::spawn(async move {
            /* use the connected client */
#           Ok::<_, std::io::Error>(())
        });
#       if true { break } // needed for type inference to work
    }

    Ok::<_, io::Error>(())
});

/* do something else not server related here */
# Ok(()) }
```

[Windows named pipe]: https://docs.microsoft.com/en-us/windows/win32/ipc/named-pipes

## tokio::net::windows::named_pipe::PipeEnd (enum)

Indicates the end of a named pipe.

## tokio::net::windows::named_pipe::PipeEnd::Client (variant)

The named pipe refers to the client end of a named pipe instance.

Corresponds to [`PIPE_CLIENT_END`].

[`PIPE_CLIENT_END`]: https://docs.rs/windows-sys/latest/windows_sys/Win32/System/Pipes/constant.PIPE_CLIENT_END.html

## tokio::net::windows::named_pipe::PipeEnd::Server (variant)

The named pipe refers to the server end of a named pipe instance.

Corresponds to [`PIPE_SERVER_END`].

[`PIPE_SERVER_END`]: https://docs.rs/windows-sys/latest/windows_sys/Win32/System/Pipes/constant.PIPE_SERVER_END.html

## tokio::net::windows::named_pipe::PipeInfo (struct)

Information about a named pipe.

Constructed through [`NamedPipeServer::info`] or [`NamedPipeClient::info`].

## tokio::net::windows::named_pipe::PipeMode (enum)

The pipe mode of a named pipe.

Set through [`ServerOptions::pipe_mode`].

## tokio::net::windows::named_pipe::PipeMode::Byte (variant)

Data is written to the pipe as a stream of bytes. The pipe does not
distinguish bytes written during different write operations.

Corresponds to [`PIPE_TYPE_BYTE`].

[`PIPE_TYPE_BYTE`]: https://docs.rs/windows-sys/latest/windows_sys/Win32/System/Pipes/constant.PIPE_TYPE_BYTE.html

## tokio::net::windows::named_pipe::PipeMode::Message (variant)

Data is written to the pipe as a stream of messages. The pipe treats the
bytes written during each write operation as a message unit. Any reading
on a named pipe returns [`ERROR_MORE_DATA`] when a message is not read
completely.

Corresponds to [`PIPE_TYPE_MESSAGE`].

[`ERROR_MORE_DATA`]: https://docs.rs/windows-sys/latest/windows_sys/Win32/Foundation/constant.ERROR_MORE_DATA.html
[`PIPE_TYPE_MESSAGE`]: https://docs.rs/windows-sys/latest/windows_sys/Win32/System/Pipes/constant.PIPE_TYPE_MESSAGE.html

## tokio::net::windows::named_pipe::ServerOptions (struct)

A builder structure for construct a named pipe with named pipe-specific
options. This is required to use for named pipe servers who wants to modify
pipe-related options.

See [`ServerOptions::create`].

## tokio::new (function)

Constructs a new `Command` for launching the program at
path `program`, with the following default configuration:

* No arguments to the program
* Inherit the current process's environment
* Inherit the current process's working directory
* Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes for `output`

Builder methods are provided to change these defaults and
otherwise configure the process.

If `program` is not an absolute path, the `PATH` will be searched in
an OS-defined way.

The search path to be used may be controlled by setting the
`PATH` environment variable on the Command,
but this has some implementation limitations on Windows
(see issue [rust-lang/rust#37519]).

### tokio::new (function) › Examples

Basic usage:

```no_run
use tokio::process::Command;
let mut command = Command::new("sh");
# let _ = command.output(); // assert borrow checker
```

[rust-lang/rust#37519]: https://github.com/rust-lang/rust/issues/37519

## tokio::new (function)

Create a new `JoinSet`.

## tokio::new (function)

Create a new `Notify`, initialized without a permit.

### tokio::new (function) › Examples

```
use tokio::sync::Notify;

let notify = Notify::new();
```

## tokio::new (function)

Creates a blank new set of options ready for configuration.

All options are initially set to `false`.

## tokio::new (function)

Creates a blank new set of options ready for configuration.

All options are initially set to `false`.

This is an async version of [`std::fs::OpenOptions::new`][std]

[std]: std::fs::OpenOptions::new

### tokio::new (function) › Examples

```no_run
use tokio::fs::OpenOptions;

let mut options = OpenOptions::new();
let future = options.read(true).open("foo.txt");
```

## tokio::new (function)

Creates a new `BufReader` with a default buffer capacity. The default is currently 8 KB,
but may change in the future.

## tokio::new (function)

Creates a new `BufWriter` with a default buffer capacity. The default is currently 8 KB,
but may change in the future.

## tokio::new (function)

Creates a new `ReadBuf` from a fully initialized buffer.

## tokio::new (function)

Creates a new barrier that can block a given number of tasks.

A barrier will block `n`-1 tasks which call [`Barrier::wait`] and then wake up all
tasks at once when the `n`th task calls `wait`.

## tokio::new (function)

Creates a new empty `OnceCell` instance.

## tokio::new (function)

Creates a new empty `SetOnce` instance.

## tokio::new (function)

Creates a new instance of an `RwLock<T>` which is unlocked.

### tokio::new (function) › Examples

```
use tokio::sync::RwLock;

let lock = RwLock::new(5);
```

## tokio::new (function)

Creates a new local runtime instance with default configuration values.

This results in the scheduler, I/O driver, and time driver being
initialized.

When a more complex configuration is necessary, the [runtime builder] may be used.

See [module level][mod] documentation for more details.

### tokio::new (function) › Examples

Creating a new `LocalRuntime` with default configuration values.

```
use tokio::runtime::LocalRuntime;

let rt = LocalRuntime::new()
    .unwrap();

// Use the runtime...
```

[mod]: crate::runtime
[runtime builder]: crate::runtime::Builder

## tokio::new (function)

Creates a new lock in an unlocked state ready for use.

### tokio::new (function) › Examples

```
use tokio::sync::Mutex;

let lock = Mutex::new(5);
```

## tokio::new (function)

Creates a new named pipe builder with the default settings.

```
use tokio::net::windows::named_pipe::ServerOptions;

const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-new";

# #[tokio::main] async fn main() -> std::io::Result<()> {
let server = ServerOptions::new().create(PIPE_NAME)?;
# Ok(()) }
```

## tokio::new (function)

Creates a new named pipe builder with the default settings.

```
use tokio::net::windows::named_pipe::{ServerOptions, ClientOptions};

const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-client-new";

# #[tokio::main] async fn main() -> std::io::Result<()> {
// Server must be created in order for the client creation to succeed.
let server = ServerOptions::new().create(PIPE_NAME)?;
let client = ClientOptions::new().open(PIPE_NAME)?;
# Ok(()) }
```

## tokio::new (function)

Creates a new runtime instance with default configuration values.

This results in the multi threaded scheduler, I/O driver, and time driver being
initialized.

Most applications will not need to call this function directly. Instead,
they will use the  [`#[tokio::main]` attribute][main]. When a more complex
configuration is necessary, the [runtime builder] may be used.

See [module level][mod] documentation for more details.

### tokio::new (function) › Examples

Creating a new `Runtime` with default configuration values.

```
use tokio::runtime::Runtime;

let rt = Runtime::new()
    .unwrap();

// Use the runtime...
```

[mod]: index.html
[main]: ../attr.main.html
[threaded scheduler]: index.html#threaded-scheduler
[runtime builder]: crate::runtime::Builder

## tokio::new (function)

Creates a new semaphore with the initial number of permits.

Panics if `permits` exceeds [`Semaphore::MAX_PERMITS`].

## tokio::new (function)

Creates a new set of options with default mode/security settings for all
platforms and also non-recursive.

This is an async version of [`std::fs::DirBuilder::new`].

### tokio::new (function) › Examples

```no_run
use tokio::fs::DirBuilder;

let builder = DirBuilder::new();
```

## tokio::new (function)

Creates a new task builder.

## tokio::new (function)

Creates an [`AsyncFd`] backed by (and taking ownership of) an object
implementing [`AsRawFd`]. The backing file descriptor is cached at the
time of creation.

Only configures the [`Interest::READABLE`] and [`Interest::WRITABLE`] interests. For more
control, use [`AsyncFd::with_interest`].

This method must be called in the context of a tokio runtime.

### tokio::new (function) › Panics

This function panics if there is no current reactor set, or if the `rt`
feature flag is not enabled.

## tokio::new (function)

Creates the sending-half of the [`broadcast`] channel.

See the documentation of [`broadcast::channel`] for more information on this method.

[`broadcast`]: crate::sync::broadcast
[`broadcast::channel`]: crate::sync::broadcast::channel

## tokio::new (function)

Creates the sending-half of the [`watch`] channel.

See documentation of [`watch::channel`] for errors when calling this function.
Beware that attempting to send a value when there are no receivers will
return an error.

[`watch`]: crate::sync::watch
[`watch::channel`]: crate::sync::watch

### tokio::new (function) › Examples
```
let sender = tokio::sync::watch::Sender::new(0u8);
assert!(sender.send(3).is_err());
let _rec = sender.subscribe();
assert!(sender.send(4).is_ok());
```

## tokio::new (function)

Returns a new local task set.

## tokio::new (function)

Wraps a type in both [`BufWriter`] and [`BufReader`].

See the documentation for those types and [`BufStream`] for details.

## tokio::new_current_thread (function)

Returns a new builder with the current thread scheduler selected.

Configuration methods can be chained on the return value.

To spawn non-`Send` tasks on the resulting runtime, combine it with a
[`LocalSet`], or call [`build_local`] to create a [`LocalRuntime`].

[`LocalSet`]: crate::task::LocalSet
[`LocalRuntime`]: crate::runtime::LocalRuntime
[`build_local`]: crate::runtime::Builder::build_local

## tokio::new_datagram (function)

Creates a new Unix datagram socket.

Calls `socket(2)` with `AF_UNIX` and `SOCK_DGRAM`.

### tokio::new_datagram (function) › Returns

On success, the newly created [`UnixSocket`] is returned. If an error is
encountered, it is returned instead.

## tokio::new_for_aio (function)

Creates a new `Aio` suitable for use with POSIX AIO functions.

It will be associated with the default reactor.  The runtime is usually
set implicitly when this function is called from a future driven by a
Tokio runtime, otherwise runtime can be set explicitly with
[`Runtime::enter`](crate::runtime::Runtime::enter) function.

## tokio::new_for_lio (function)

Creates a new `Aio` suitable for use with [`lio_listio`].

It will be associated with the default reactor.  The runtime is usually
set implicitly when this function is called from a future driven by a
Tokio runtime, otherwise runtime can be set explicitly with
[`Runtime::enter`](crate::runtime::Runtime::enter) function.

[`lio_listio`]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/lio_listio.html

## tokio::new_multi_thread (function)

Returns a new builder with the multi thread scheduler selected.

Configuration methods can be chained on the return value.

## tokio::new_stream (function)

Creates a new Unix stream socket.

Calls `socket(2)` with `AF_UNIX` and `SOCK_STREAM`.

### tokio::new_stream (function) › Returns

On success, the newly created [`UnixSocket`] is returned. If an error is
encountered, it is returned instead.

## tokio::new_unsplit (function)

Creates unidirectional buffer that acts like in memory pipe. To create split
version with separate reader and writer you can use [`simplex`] function.

The `max_buf_size` argument is the maximum amount of bytes that can be
written to a buffer before it returns `Poll::Pending`.

## tokio::new_v4 (function)

Creates a new socket configured for IPv4.

Calls `socket(2)` with `AF_INET` and `SOCK_STREAM`.

### tokio::new_v4 (function) › Returns

On success, the newly created `TcpSocket` is returned. If an error is
encountered, it is returned instead.

### tokio::new_v4 (function) › Examples

Create a new IPv4 socket and start listening.

```no_run
use tokio::net::TcpSocket;

use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let addr = "127.0.0.1:8080".parse().unwrap();
    let socket = TcpSocket::new_v4()?;
    socket.bind(addr)?;

    let listener = socket.listen(128)?;
# drop(listener);
    Ok(())
}
```

## tokio::new_v6 (function)

Creates a new socket configured for IPv6.

Calls `socket(2)` with `AF_INET6` and `SOCK_STREAM`.

### tokio::new_v6 (function) › Returns

On success, the newly created `TcpSocket` is returned. If an error is
encountered, it is returned instead.

### tokio::new_v6 (function) › Examples

Create a new IPv6 socket and start listening.

```no_run
use tokio::net::TcpSocket;

use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let addr = "[::1]:8080".parse().unwrap();
    let socket = TcpSocket::new_v6()?;
    socket.bind(addr)?;

    let listener = socket.listen(128)?;
# drop(listener);
    Ok(())
}
```

## tokio::new_with (function)

Creates a new `OnceCell` that contains the provided value, if any.

If the `Option` is `None`, this is equivalent to `OnceCell::new`.

[`OnceCell::new`]: crate::sync::OnceCell::new

## tokio::new_with (function)

Creates a new `SetOnce` that contains the provided value, if any.

If the `Option` is `None`, this is equivalent to `SetOnce::new`.

[`SetOnce::new`]: crate::sync::SetOnce::new

## tokio::next_entry (function)

Returns the next entry in the directory stream.

### tokio::next_entry (function) › Cancel safety

This method is cancel safe.

## tokio::next_line (function)

Returns the next line in the stream.

### tokio::next_line (function) › Cancel safety

This method is cancel safe.

### tokio::next_line (function) › Examples

```
# use tokio::io::AsyncBufRead;
use tokio::io::AsyncBufReadExt;

# async fn dox(my_buf_read: impl AsyncBufRead + Unpin) -> std::io::Result<()> {
let mut lines = my_buf_read.lines();

while let Some(line) = lines.next_line().await? {
    println!("length = {}", line.len())
}
# Ok(())
# }
```

## tokio::next_segment (function)

Returns the next segment in the stream.

### tokio::next_segment (function) › Examples

```
# use tokio::io::AsyncBufRead;
use tokio::io::AsyncBufReadExt;

# async fn dox(my_buf_read: impl AsyncBufRead + Unpin) -> std::io::Result<()> {
let mut segments = my_buf_read.split(b'f');

while let Some(segment) = segments.next_segment().await? {
    println!("length = {}", segment.len())
}
# Ok(())
# }
```

## tokio::nodelay (function)

Gets the value of the `TCP_NODELAY` option on this socket.

For more information about this option, see [`set_nodelay`].

[`set_nodelay`]: TcpSocket::set_nodelay

### tokio::nodelay (function) › Examples

```no_run
use tokio::net::TcpSocket;

# async fn dox() -> Result<(), Box<dyn std::error::Error>> {
let socket = TcpSocket::new_v4()?;

println!("{:?}", socket.nodelay()?);
# Ok(())
# }
```

## tokio::nodelay (function)

Gets the value of the `TCP_NODELAY` option on this socket.

For more information about this option, see [`set_nodelay`].

[`set_nodelay`]: TcpStream::set_nodelay

### tokio::nodelay (function) › Examples

```no_run
use tokio::net::TcpStream;

# async fn dox() -> Result<(), Box<dyn std::error::Error>> {
let stream = TcpStream::connect("127.0.0.1:8080").await?;

println!("{:?}", stream.nodelay()?);
# Ok(())
# }
```

## tokio::notified (function)

Wait for a notification.

Equivalent to:

```ignore
async fn notified(&self);
```

Each `Notify` value holds a single permit. If a permit is available from
an earlier call to [`notify_one()`], then `notified().await` will complete
immediately, consuming that permit. Otherwise, `notified().await` waits
for a permit to be made available by the next call to `notify_one()`.

The `Notified` future is not guaranteed to receive wakeups from calls to
`notify_one()` if it has not yet been polled. See the documentation for
[`Notified::enable()`] for more details.

The `Notified` future is guaranteed to receive wakeups from
`notify_waiters()` as soon as it has been created, even if it has not
yet been polled.

[`notify_one()`]: Notify::notify_one
[`Notified::enable()`]: Notified::enable

### tokio::notified (function) › Cancel safety

This method uses a queue to fairly distribute notifications in the order
they were requested. Cancelling a call to `notified` makes you lose your
place in the queue.

### tokio::notified (function) › Examples

```
use tokio::sync::Notify;
use std::sync::Arc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let notify = Arc::new(Notify::new());
let notify2 = notify.clone();

tokio::spawn(async move {
    notify2.notified().await;
    println!("received notification");
});

println!("sending notification");
notify.notify_one();
# }
```

## tokio::notified_owned (function)

Wait for a notification with an owned `Future`.

Unlike [`Self::notified`] which returns a future tied to the `Notify`'s
lifetime, `notified_owned` creates a self-contained future that owns its
notification state, making it safe to move between threads.

See [`Self::notified`] for more details.

### tokio::notified_owned (function) › Cancel safety

This method uses a queue to fairly distribute notifications in the order
they were requested. Cancelling a call to `notified_owned` makes you lose your
place in the queue.

### tokio::notified_owned (function) › Examples

```
use std::sync::Arc;
use tokio::sync::Notify;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let notify = Arc::new(Notify::new());

for _ in 0..10 {
    let notified = notify.clone().notified_owned();
    tokio::spawn(async move {
        notified.await;
        println!("received notification");
    });
}

println!("sending notification");
notify.notify_waiters();
# }
```

## tokio::notify_last (function)

Notifies the last waiting task.

This function behaves similar to `notify_one`. The only difference is that it wakes
the most recently added waiter instead of the oldest waiter.

Check the [`notify_one()`] documentation for more info and
examples.

[`notify_one()`]: Notify::notify_one

## tokio::notify_one (function)

Notifies the first waiting task.

If a task is currently waiting, that task is notified. Otherwise, a
permit is stored in this `Notify` value and the **next** call to
[`notified().await`] will complete immediately consuming the permit made
available by this call to `notify_one()`.

At most one permit may be stored by `Notify`. Many sequential calls to
`notify_one` will result in a single permit being stored. The next call to
`notified().await` will complete immediately, but the one after that
will wait.

[`notified().await`]: Notify::notified()

### tokio::notify_one (function) › Examples

```
use tokio::sync::Notify;
use std::sync::Arc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let notify = Arc::new(Notify::new());
let notify2 = notify.clone();

tokio::spawn(async move {
    notify2.notified().await;
    println!("received notification");
});

println!("sending notification");
notify.notify_one();
# }
```

## tokio::notify_waiters (function)

Notifies all waiting tasks.

If a task is currently waiting, that task is notified. Unlike with
`notify_one()`, no permit is stored to be used by the next call to
`notified().await`. The purpose of this method is to notify all
already registered waiters. Registering for notification is done by
acquiring an instance of the `Notified` future via calling `notified()`.

### tokio::notify_waiters (function) › Examples

```
use tokio::sync::Notify;
use std::sync::Arc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let notify = Arc::new(Notify::new());
let notify2 = notify.clone();

let notified1 = notify.notified();
let notified2 = notify.notified();

let handle = tokio::spawn(async move {
    println!("sending notifications");
    notify2.notify_waiters();
});

notified1.await;
notified2.await;
println!("received notifications");
# }
```

## tokio::now (function)

Returns an instant corresponding to "now".

### tokio::now (function) › Examples

```
use tokio::time::Instant;

let now = Instant::now();
```

## tokio::num_alive_tasks (function)

Returns the current number of alive tasks in the runtime.

This counter increases when a task is spawned and decreases when a
task exits.

Note: When using the multi-threaded runtime this number may not
not have strong consistency i.e. no tasks may be running but the metric
reports otherwise.

### tokio::num_alive_tasks (function) › Examples

```
use tokio::runtime::Handle;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let metrics = Handle::current().metrics();

let n = metrics.num_alive_tasks();
println!("Runtime has {} alive tasks", n);
# }
```

## tokio::num_blocking_threads (function)

Returns the number of additional threads spawned by the runtime.

The number of workers is set by configuring `max_blocking_threads` on
`runtime::Builder`.

### tokio::num_blocking_threads (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime::Handle;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let _ = tokio::task::spawn_blocking(move || {
    // Stand-in for compute-heavy work or using synchronous APIs
    1 + 1
}).await;
let metrics = Handle::current().metrics();

let n = metrics.num_blocking_threads();
println!("Runtime has created {} threads", n);
# }
# }
```

## tokio::num_idle_blocking_threads (function)

Returns the number of idle threads, which have spawned by the runtime
for `spawn_blocking` calls.

### tokio::num_idle_blocking_threads (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime::Handle;

#[tokio::main]
async fn main() {
    let _ = tokio::task::spawn_blocking(move || {
        // Stand-in for compute-heavy work or using synchronous APIs
        1 + 1
    }).await;
    let metrics = Handle::current().metrics();

    let n = metrics.num_idle_blocking_threads();
    println!("Runtime has {} idle blocking thread pool threads", n);
}
# }
```

## tokio::num_permits (function)

Returns the number of permits held by `self`.

## tokio::num_permits (function)

Returns the number of permits held by `self`.

## tokio::num_workers (function)

Returns the number of worker threads used by the runtime.

The number of workers is set by configuring `worker_threads` on
`runtime::Builder`. When using the `current_thread` runtime, the return
value is always `1`.

### tokio::num_workers (function) › Examples

```
use tokio::runtime::Handle;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let metrics = Handle::current().metrics();

let n = metrics.num_workers();
println!("Runtime is using {} workers", n);
# }
```

## tokio::on_after_task_poll (function)

Executes function `f` just after a task is polled

`f` is called within the Tokio context, so functions like
[`tokio::spawn`](crate::spawn) can be called, and may result in this callback being
invoked immediately.

**Note**: This is an [unstable API][unstable]. The public API of this type
may break in 1.x releases. See [the documentation on unstable
features][unstable] for details.

[unstable]: crate#unstable-features

### tokio::on_after_task_poll (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
# use std::sync::{atomic::AtomicUsize, Arc};
# use tokio::task::yield_now;
# pub fn main() {
let poll_stop_counter = Arc::new(AtomicUsize::new(0));
let poll_stop = poll_stop_counter.clone();
let rt = tokio::runtime::Builder::new_multi_thread()
    .enable_all()
    .on_after_task_poll(move |meta| {
        println!("task {} completed polling", meta.id());
    })
    .build()
    .unwrap();
let task = rt.spawn(async {
    yield_now().await;
});
let _ = rt.block_on(task);

# }
# }
```

## tokio::on_before_task_poll (function)

Executes function `f` just before a task is polled

`f` is called within the Tokio context, so functions like
[`tokio::spawn`](crate::spawn) can be called, and may result in this callback being
invoked immediately.

**Note**: This is an [unstable API][unstable]. The public API of this type
may break in 1.x releases. See [the documentation on unstable
features][unstable] for details.

[unstable]: crate#unstable-features

### tokio::on_before_task_poll (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
# use std::sync::{atomic::AtomicUsize, Arc};
# use tokio::task::yield_now;
# pub fn main() {
let poll_start_counter = Arc::new(AtomicUsize::new(0));
let poll_start = poll_start_counter.clone();
let rt = tokio::runtime::Builder::new_multi_thread()
    .enable_all()
    .on_before_task_poll(move |meta| {
        println!("task {} is about to be polled", meta.id())
    })
    .build()
    .unwrap();
let task = rt.spawn(async {
    yield_now().await;
});
let _ = rt.block_on(task);

# }
# }
```

## tokio::on_task_spawn (function)

Executes function `f` just before a task is spawned.

`f` is called within the Tokio context, so functions like
[`tokio::spawn`](crate::spawn) can be called, and may result in this callback being
invoked immediately.

This can be used for bookkeeping or monitoring purposes.

Note: There can only be one spawn callback for a runtime; calling this function more
than once replaces the last callback defined, rather than adding to it.

This *does not* support [`LocalSet`](crate::task::LocalSet) at this time.

**Note**: This is an [unstable API][unstable]. The public API of this type
may break in 1.x releases. See [the documentation on unstable
features][unstable] for details.

[unstable]: crate#unstable-features

### tokio::on_task_spawn (function) › Examples

```
# use tokio::runtime;
# pub fn main() {
let runtime = runtime::Builder::new_current_thread()
    .on_task_spawn(|_| {
        println!("spawning task");
    })
    .build()
    .unwrap();

runtime.block_on(async {
    tokio::task::spawn(std::future::ready(()));

    for _ in 0..64 {
        tokio::task::yield_now().await;
    }
})
# }
```

## tokio::on_task_terminate (function)

Executes function `f` just after a task is terminated.

`f` is called within the Tokio context, so functions like
[`tokio::spawn`](crate::spawn) can be called.

This can be used for bookkeeping or monitoring purposes.

Note: There can only be one task termination callback for a runtime; calling this
function more than once replaces the last callback defined, rather than adding to it.

This *does not* support [`LocalSet`](crate::task::LocalSet) at this time.

**Note**: This is an [unstable API][unstable]. The public API of this type
may break in 1.x releases. See [the documentation on unstable
features][unstable] for details.

[unstable]: crate#unstable-features

### tokio::on_task_terminate (function) › Examples

```
# use tokio::runtime;
# pub fn main() {
let runtime = runtime::Builder::new_current_thread()
    .on_task_terminate(|_| {
        println!("killing task");
    })
    .build()
    .unwrap();

runtime.block_on(async {
    tokio::task::spawn(std::future::ready(()));

    for _ in 0..64 {
        tokio::task::yield_now().await;
    }
})
# }
```

## tokio::on_thread_park (function)

Executes function `f` just before a thread is parked (goes idle).
`f` is called within the Tokio context, so functions like [`tokio::spawn`](crate::spawn)
can be called, and may result in this thread being unparked immediately.

This can be used to start work only when the executor is idle, or for bookkeeping
and monitoring purposes.

Note: There can only be one park callback for a runtime; calling this function
more than once replaces the last callback defined, rather than adding to it.

### tokio::on_thread_park (function) › Examples

### tokio::on_thread_park (function) › Multithreaded executor
```
# #[cfg(not(target_family = "wasm"))]
# {
# use std::sync::Arc;
# use std::sync::atomic::{AtomicBool, Ordering};
# use tokio::runtime;
# use tokio::sync::Barrier;
# pub fn main() {
let once = AtomicBool::new(true);
let barrier = Arc::new(Barrier::new(2));

let runtime = runtime::Builder::new_multi_thread()
    .worker_threads(1)
    .on_thread_park({
        let barrier = barrier.clone();
        move || {
            let barrier = barrier.clone();
            if once.swap(false, Ordering::Relaxed) {
                tokio::spawn(async move { barrier.wait().await; });
           }
        }
    })
    .build()
    .unwrap();

runtime.block_on(async {
   barrier.wait().await;
})
# }
# }
```
### tokio::on_thread_park (function) › Current thread executor
```
# use std::sync::Arc;
# use std::sync::atomic::{AtomicBool, Ordering};
# use tokio::runtime;
# use tokio::sync::Barrier;
# pub fn main() {
let once = AtomicBool::new(true);
let barrier = Arc::new(Barrier::new(2));

let runtime = runtime::Builder::new_current_thread()
    .on_thread_park({
        let barrier = barrier.clone();
        move || {
            let barrier = barrier.clone();
            if once.swap(false, Ordering::Relaxed) {
                tokio::spawn(async move { barrier.wait().await; });
           }
        }
    })
    .build()
    .unwrap();

runtime.block_on(async {
   barrier.wait().await;
})
# }
```

## tokio::on_thread_start (function)

Executes function `f` after each thread is started but before it starts
doing work.

This is intended for bookkeeping and monitoring use cases.

### tokio::on_thread_start (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
# use tokio::runtime;
# pub fn main() {
let runtime = runtime::Builder::new_multi_thread()
    .on_thread_start(|| {
        println!("thread started");
    })
    .build();
# }
# }
```

## tokio::on_thread_stop (function)

Executes function `f` before each thread stops.

This is intended for bookkeeping and monitoring use cases.

### tokio::on_thread_stop (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
{
# use tokio::runtime;
# pub fn main() {
let runtime = runtime::Builder::new_multi_thread()
    .on_thread_stop(|| {
        println!("thread stopping");
    })
    .build();
# }
# }
```

## tokio::on_thread_unpark (function)

Executes function `f` just after a thread unparks (starts executing tasks).

This is intended for bookkeeping and monitoring use cases; note that work
in this callback will increase latencies when the application has allowed one or
more runtime threads to go idle.

Note: There can only be one unpark callback for a runtime; calling this function
more than once replaces the last callback defined, rather than adding to it.

### tokio::on_thread_unpark (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
# use tokio::runtime;
# pub fn main() {
let runtime = runtime::Builder::new_multi_thread()
    .on_thread_unpark(|| {
        println!("thread unparking");
    })
    .build();

runtime.unwrap().block_on(async {
   tokio::task::yield_now().await;
   println!("Hello from Tokio!");
})
# }
# }
```

## tokio::open (function)

Attempts to open a file in read-only mode.

See [`OpenOptions`] for more details.

### tokio::open (function) › Errors

This function will return an error if called from outside of the Tokio
runtime or if path does not already exist. Other errors may also be
returned according to `OpenOptions::open`.

### tokio::open (function) › Examples

```no_run
use tokio::fs::File;
use tokio::io::AsyncReadExt;

# async fn dox() -> std::io::Result<()> {
let mut file = File::open("foo.txt").await?;

let mut contents = vec![];
file.read_to_end(&mut contents).await?;

println!("len = {}", contents.len());
# Ok(())
# }
```

The [`read_to_end`] method is defined on the [`AsyncReadExt`] trait.

[`read_to_end`]: fn@crate::io::AsyncReadExt::read_to_end
[`AsyncReadExt`]: trait@crate::io::AsyncReadExt

## tokio::open (function)

Opens a file at `path` with the options specified by `self`.

This is an async version of [`std::fs::OpenOptions::open`][std]

[std]: std::fs::OpenOptions::open

### tokio::open (function) › Errors

This function will return an error under a number of different
circumstances. Some of these error conditions are listed here, together
with their [`ErrorKind`]. The mapping to [`ErrorKind`]s is not part of
the compatibility contract of the function, especially the `Other` kind
might change to more specific kinds in the future.

* [`NotFound`]: The specified file does not exist and neither `create`
  or `create_new` is set.
* [`NotFound`]: One of the directory components of the file path does
  not exist.
* [`PermissionDenied`]: The user lacks permission to get the specified
  access rights for the file.
* [`PermissionDenied`]: The user lacks permission to open one of the
  directory components of the specified path.
* [`AlreadyExists`]: `create_new` was specified and the file already
  exists.
* [`InvalidInput`]: Invalid combinations of open options (truncate
  without write access, no access mode set, etc.).
* [`Other`]: One of the directory components of the specified file path
  was not, in fact, a directory.
* [`Other`]: Filesystem-level errors: full disk, write permission
  requested on a read-only file system, exceeded disk quota, too many
  open files, too long filename, too many symbolic links in the
  specified path (Unix-like systems only), etc.

### tokio::open (function) › io_uring support

On Linux, you can also use `io_uring` for executing system calls.
To enable `io_uring`, you need to specify the `--cfg tokio_unstable`
flag at compile time, enable the `io-uring` cargo feature, and set the
`Builder::enable_io_uring` runtime option.

Support for `io_uring` is currently experimental, so its behavior may
change or it may be removed in future versions.

### tokio::open (function) › Examples

```no_run
use tokio::fs::OpenOptions;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let file = OpenOptions::new().open("foo.txt").await?;
    Ok(())
}
```

[`ErrorKind`]: std::io::ErrorKind
[`AlreadyExists`]: std::io::ErrorKind::AlreadyExists
[`InvalidInput`]: std::io::ErrorKind::InvalidInput
[`NotFound`]: std::io::ErrorKind::NotFound
[`Other`]: std::io::ErrorKind::Other
[`PermissionDenied`]: std::io::ErrorKind::PermissionDenied

## tokio::open (function)

Opens the named pipe identified by `addr`.

This opens the client using [`CreateFile`] with the
`dwCreationDisposition` option set to `OPEN_EXISTING`.

[`CreateFile`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea

### tokio::open (function) › Errors

This errors if called outside of a [Tokio Runtime], or in a runtime that
has not [enabled I/O], or if any OS-specific I/O errors occur.

There are a few errors you need to take into account when creating a
named pipe on the client side:

* [`std::io::ErrorKind::NotFound`] - This indicates that the named pipe
  does not exist. Presumably the server is not up.
* [`ERROR_PIPE_BUSY`] - This error is raised when the named pipe exists,
  but the server is not currently waiting for a connection. Please see the
  examples for how to check for this error.

[`ERROR_PIPE_BUSY`]: https://docs.rs/windows-sys/latest/windows_sys/Win32/Foundation/constant.ERROR_PIPE_BUSY.html
[enabled I/O]: crate::runtime::Builder::enable_io
[Tokio Runtime]: crate::runtime::Runtime

A connect loop that waits until a pipe becomes available looks like
this:

```no_run
use std::time::Duration;
use tokio::net::windows::named_pipe::ClientOptions;
use tokio::time;
use windows_sys::Win32::Foundation::ERROR_PIPE_BUSY;

const PIPE_NAME: &str = r"\\.\pipe\mynamedpipe";

# #[tokio::main] async fn main() -> std::io::Result<()> {
let client = loop {
    match ClientOptions::new().open(PIPE_NAME) {
        Ok(client) => break client,
        Err(e) if e.raw_os_error() == Some(ERROR_PIPE_BUSY as i32) => (),
        Err(e) => return Err(e),
    }

    time::sleep(Duration::from_millis(50)).await;
};

// use the connected client.
# Ok(()) }
```

## tokio::open_receiver (function)

Creates a [`Receiver`] from a FIFO file with the options specified by `self`.

This function will open the FIFO file at the specified path, possibly
check if it is a pipe, and associate the pipe with the default event
loop for reading.

### tokio::open_receiver (function) › Errors

If the file type check fails, this function will fail with `io::ErrorKind::InvalidInput`.
This function may also fail with other standard OS errors.

### tokio::open_receiver (function) › Panics

This function panics if it is not called from within a runtime with
IO enabled.

The runtime is usually set implicitly when this function is called
from a future driven by a tokio runtime, otherwise runtime can be set
explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.

## tokio::open_sender (function)

Creates a [`Sender`] from a FIFO file with the options specified by `self`.

This function will open the FIFO file at the specified path, possibly
check if it is a pipe, and associate the pipe with the default event
loop for writing.

### tokio::open_sender (function) › Errors

If the file type check fails, this function will fail with `io::ErrorKind::InvalidInput`.
If the file is not opened in read-write access mode and the file is not
currently open for reading, this function will fail with `ENXIO`.
This function may also fail with other standard OS errors.

### tokio::open_sender (function) › Panics

This function panics if it is not called from within a runtime with
IO enabled.

The runtime is usually set implicitly when this function is called
from a future driven by a tokio runtime, otherwise runtime can be set
explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.

## tokio::open_with_security_attributes_raw (function)

Opens the named pipe identified by `addr`.

This is the same as [`open`] except that it supports providing the raw
pointer to a structure of [`SECURITY_ATTRIBUTES`] which will be passed
as the `lpSecurityAttributes` argument to [`CreateFile`].

### tokio::open_with_security_attributes_raw (function) › Safety

The `attrs` argument must either be null or point at a valid instance of
the [`SECURITY_ATTRIBUTES`] structure. If the argument is null, the
behavior is identical to calling the [`open`] method.

[`open`]: ClientOptions::open
[`CreateFile`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew
[`SECURITY_ATTRIBUTES`]: https://docs.rs/windows-sys/latest/windows_sys/Win32/Security/struct.SECURITY_ATTRIBUTES.html

## tokio::options (function)

Returns a new [`OpenOptions`] object.

This function returns a new `OpenOptions` object that you can use to
open or create a file with specific options if `open()` or `create()`
are not appropriate.

It is equivalent to `OpenOptions::new()`, but allows you to write more
readable code. Instead of
`OpenOptions::new().append(true).open("example.log")`,
you can write `File::options().append(true).open("example.log")`. This
also avoids the need to import `OpenOptions`.

See the [`OpenOptions::new`] function for more details.

### tokio::options (function) › Examples

```no_run
use tokio::fs::File;
use tokio::io::AsyncWriteExt;

# async fn dox() -> std::io::Result<()> {
let mut f = File::options().append(true).open("example.log").await?;
f.write_all(b"new line\n").await?;
# Ok(())
# }
```

## tokio::out_buffer_size (function)

The number of bytes to reserve for the output buffer.

This corresponds to specifying [`nOutBufferSize`].

[`nOutBufferSize`]: https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createnamedpipea

## tokio::out_buffer_size (struct_field)

The number of bytes to reserve for the output buffer.

## tokio::output (function)

Executes the command as a child process, waiting for it to finish and
collecting all of its output.

> **Note**: this method, unlike the standard library, will
> unconditionally configure the stdout/stderr handles to be pipes, even
> if they have been previously configured. If this is not desired then
> the `spawn` method should be used in combination with the
> `wait_with_output` method on child.

This method will return a future representing the collection of the
child process's stdout/stderr. It will resolve to
the `Output` type in the standard library, containing `stdout` and
`stderr` as `Vec<u8>` along with an `ExitStatus` representing how the
process exited.

All I/O this child does will be associated with the current default
event loop.

The destructor of the future returned by this function will kill
the child if [`kill_on_drop`] is set to true.

[`kill_on_drop`]: fn@Self::kill_on_drop

### tokio::output (function) › Errors

This future will return an error if the child process cannot be spawned
or if there is an error while awaiting its status.

On Unix platforms this method will fail with `std::io::ErrorKind::WouldBlock`
if the system process limit is reached (which includes other applications
running on the system).
### tokio::output (function) › Examples

Basic usage:

```no_run
use tokio::process::Command;

async fn run_ls() {
    let output: std::process::Output = Command::new("ls")
        .output()
        .await
        .expect("ls command failed to run");
    println!("stderr of ls: {:?}", output.stderr);
}
```

## tokio::pair (function)

Creates an unnamed pair of connected sockets.

This function will create a pair of interconnected Unix sockets for
communicating back and forth between one another. Each socket will
be associated with the default event loop's handle.

## tokio::path (function)

Returns the full path to the file that this entry represents.

The full path is created by joining the original path to `read_dir`
with the filename of this entry.

### tokio::path (function) › Examples

```no_run
use tokio::fs;

# async fn dox() -> std::io::Result<()> {
let mut entries = fs::read_dir(".").await?;

while let Some(entry) = entries.next_entry().await? {
    println!("{:?}", entry.path());
}
# Ok(())
# }
```

This prints output like:

```text
"./whatever.txt"
"./foo.html"
"./hello_world.rs"
```

The exact text, of course, depends on what files you have in `.`.

## tokio::peek (function)

Receives a single datagram from the connected address without removing it from the queue.
On success, returns the number of bytes read from whence the data came.

### tokio::peek (function) › Notes

On Windows, if the data is larger than the buffer specified, the buffer
is filled with the first part of the data, and peek returns the error
`WSAEMSGSIZE(10040)`. The excess data is lost.
Make sure to always use a sufficiently large buffer to hold the
maximum UDP packet size, which can be up to 65536 bytes in size.

MacOS will return an error if you pass a zero-sized buffer.

If you're merely interested in learning the sender of the data at the head of the queue,
try [`peek_sender`].

Note that the socket address **cannot** be implicitly trusted, because it is relatively
trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
Because UDP is stateless and does not validate the origin of a packet,
the attacker does not need to be able to intercept traffic in order to interfere.
It is important to be aware of this when designing your application-level protocol.

### tokio::peek (function) › Examples

```no_run
use tokio::net::UdpSocket;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let socket = UdpSocket::bind("127.0.0.1:8080").await?;

    let mut buf = vec![0u8; 32];
    let len = socket.peek(&mut buf).await?;

    println!("peeked {:?} bytes", len);

    Ok(())
}
```

[`peek_sender`]: method@Self::peek_sender
[packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection

## tokio::peek (function)

Receives data on the socket from the remote address to which it is
connected, without removing that data from the queue. On success,
returns the number of bytes peeked.

See the [`TcpStream::peek`] level documentation for more details.

[`TcpStream::peek`]: TcpStream::peek

### tokio::peek (function) › Examples

```no_run
use tokio::net::TcpStream;
use tokio::io::AsyncReadExt;
use std::error::Error;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // Connect to a peer
    let mut stream = TcpStream::connect("127.0.0.1:8080").await?;
    let (mut read_half, _) = stream.split();

    let mut b1 = [0; 10];
    let mut b2 = [0; 10];

    // Peek at the data
    let n = read_half.peek(&mut b1).await?;

    // Read the data
    assert_eq!(n, read_half.read(&mut b2[..n]).await?);
    assert_eq!(&b1[..n], &b2[..n]);

    Ok(())
}
```

The [`read`] method is defined on the [`AsyncReadExt`] trait.

[`read`]: fn@crate::io::AsyncReadExt::read
[`AsyncReadExt`]: trait@crate::io::AsyncReadExt

## tokio::peek (function)

Receives data on the socket from the remote address to which it is
connected, without removing that data from the queue. On success,
returns the number of bytes peeked.

See the [`TcpStream::peek`] level documentation for more details.

[`TcpStream::peek`]: TcpStream::peek

### tokio::peek (function) › Examples

```no_run
use tokio::net::TcpStream;
use tokio::io::AsyncReadExt;
use std::error::Error;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // Connect to a peer
    let stream = TcpStream::connect("127.0.0.1:8080").await?;
    let (mut read_half, _) = stream.into_split();

    let mut b1 = [0; 10];
    let mut b2 = [0; 10];

    // Peek at the data
    let n = read_half.peek(&mut b1).await?;

    // Read the data
    assert_eq!(n, read_half.read(&mut b2[..n]).await?);
    assert_eq!(&b1[..n], &b2[..n]);

    Ok(())
}
```

The [`read`] method is defined on the [`AsyncReadExt`] trait.

[`read`]: fn@crate::io::AsyncReadExt::read
[`AsyncReadExt`]: trait@crate::io::AsyncReadExt

## tokio::peek (function)

Receives data on the socket from the remote address to which it is
connected, without removing that data from the queue. On success,
returns the number of bytes peeked.

Successive calls return the same data. This is accomplished by passing
`MSG_PEEK` as a flag to the underlying `recv` system call.

### tokio::peek (function) › Cancel safety

This method is cancel safe. If the method is used as a branch in
[`tokio::select!`](crate::select) and another branch
completes first, then it is guaranteed that no peek was performed, and
that `buf` has not been modified.

### tokio::peek (function) › Examples

```no_run
use tokio::net::TcpStream;
use tokio::io::AsyncReadExt;
use std::error::Error;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // Connect to a peer
    let mut stream = TcpStream::connect("127.0.0.1:8080").await?;

    let mut b1 = [0; 10];
    let mut b2 = [0; 10];

    // Peek at the data
    let n = stream.peek(&mut b1).await?;

    // Read the data
    assert_eq!(n, stream.read(&mut b2[..n]).await?);
    assert_eq!(&b1[..n], &b2[..n]);

    Ok(())
}
```

The [`read`] method is defined on the [`AsyncReadExt`] trait.

[`read`]: fn@crate::io::AsyncReadExt::read
[`AsyncReadExt`]: trait@crate::io::AsyncReadExt

## tokio::peek_from (function)

Receives data from the socket, without removing it from the input queue.
On success, returns the number of bytes read and the address from whence
the data came.

### tokio::peek_from (function) › Notes

On Windows, if the data is larger than the buffer specified, the buffer
is filled with the first part of the data, and `peek_from` returns the error
`WSAEMSGSIZE(10040)`. The excess data is lost.
Make sure to always use a sufficiently large buffer to hold the
maximum UDP packet size, which can be up to 65536 bytes in size.

MacOS will return an error if you pass a zero-sized buffer.

If you're merely interested in learning the sender of the data at the head of the queue,
try [`peek_sender`].

Note that the socket address **cannot** be implicitly trusted, because it is relatively
trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
Because UDP is stateless and does not validate the origin of a packet,
the attacker does not need to be able to intercept traffic in order to interfere.
It is important to be aware of this when designing your application-level protocol.

### tokio::peek_from (function) › Examples

```no_run
use tokio::net::UdpSocket;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let socket = UdpSocket::bind("127.0.0.1:8080").await?;

    let mut buf = vec![0u8; 32];
    let (len, addr) = socket.peek_from(&mut buf).await?;

    println!("peeked {:?} bytes from {:?}", len, addr);

    Ok(())
}
```

[`peek_sender`]: method@Self::peek_sender
[packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection

## tokio::peek_sender (function)

Retrieve the sender of the data at the head of the input queue, waiting if empty.

This is equivalent to calling [`peek_from`] with a zero-sized buffer,
but suppresses the `WSAEMSGSIZE` error on Windows and the "invalid argument" error on macOS.

Note that the socket address **cannot** be implicitly trusted, because it is relatively
trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
Because UDP is stateless and does not validate the origin of a packet,
the attacker does not need to be able to intercept traffic in order to interfere.
It is important to be aware of this when designing your application-level protocol.

[`peek_from`]: method@Self::peek_from
[packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection

## tokio::peer_addr (function)

Returns the remote address that this stream is connected to.

## tokio::peer_addr (function)

Returns the remote address that this stream is connected to.

## tokio::peer_addr (function)

Returns the remote address that this stream is connected to.

## tokio::peer_addr (function)

Returns the remote address that this stream is connected to.

## tokio::peer_addr (function)

Returns the remote address that this stream is connected to.

### tokio::peer_addr (function) › Examples

```no_run
use tokio::net::TcpStream;

# async fn dox() -> Result<(), Box<dyn std::error::Error>> {
let stream = TcpStream::connect("127.0.0.1:8080").await?;

println!("{:?}", stream.peer_addr()?);
# Ok(())
# }
```

## tokio::peer_addr (function)

Returns the socket address of the remote half of this connection.

## tokio::peer_addr (function)

Returns the socket address of the remote half of this connection.

## tokio::peer_addr (function)

Returns the socket address of the remote half of this connection.

## tokio::peer_addr (function)

Returns the socket address of the remote half of this connection.

## tokio::peer_addr (function)

Returns the socket address of the remote half of this connection.

### tokio::peer_addr (function) › Examples

```no_run
use tokio::net::UnixStream;

# async fn dox() -> Result<(), Box<dyn std::error::Error>> {
let dir = tempfile::tempdir().unwrap();
let bind_path = dir.path().join("bind_path");
let stream = UnixStream::connect(bind_path).await?;

println!("{:?}", stream.peer_addr()?);
# Ok(())
# }
```

## tokio::peer_addr (function)

Returns the socket address of the remote peer this socket was connected to.

### tokio::peer_addr (function) › Example

```
use tokio::net::UdpSocket;

# use std::{io, net::SocketAddr};
# #[tokio::main]
# async fn main() -> io::Result<()> {
# if cfg!(miri) { return Ok(()); } // No UDP sockets in miri.
let addr = "0.0.0.0:8080".parse::<SocketAddr>().unwrap();
let peer = "127.0.0.1:11100".parse::<SocketAddr>().unwrap();
let sock = UdpSocket::bind(addr).await?;
sock.connect(peer).await?;
assert_eq!(peer, sock.peer_addr()?);
#    Ok(())
# }
```

## tokio::peer_cred (function)

Returns effective credentials of the process which called `connect` or `pair`.

## tokio::period (function)

Returns the period of the interval.

## tokio::pid (function)

Gets PID (process ID) of the process.

This is implemented under Linux, Android, OpenBSD, FreeBSD (since
FreeBSD 13), NetBSD, NTO, iOS, macOS, tvOS, watchOS, visionOS,
Solaris, Illumos, Cygwin, Haiku, and Redox. On other platforms this
will always return `None`.

## tokio::pin (macro)

Pins a value on the stack.

Calls to `async fn` return anonymous [`Future`] values that are `!Unpin`.
These values must be pinned before they can be polled. Calling `.await` will
handle this, but consumes the future. If it is required to call `.await` on
a `&mut _` reference, the caller is responsible for pinning the future.

Pinning may be done by allocating with [`Box::pin`] or by using the stack
with the `pin!` macro.

The following will **fail to compile**:

```compile_fail
async fn my_async_fn() {
    // async logic here
}

#[tokio::main]
async fn main() {
    let mut future = my_async_fn();
    (&mut future).await;
}
```

To make this work requires pinning:

```
use tokio::pin;

async fn my_async_fn() {
    // async logic here
}

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let future = my_async_fn();
pin!(future);

(&mut future).await;
# }
```

Pinning is useful when using `select!` and stream operators that require `T:
Stream + Unpin`.

[`Future`]: trait@std::future::Future
[`Box::pin`]: std::boxed::Box::pin

### tokio::pin (macro) › Usage

The `pin!` macro takes **identifiers** as arguments. It does **not** work
with expressions.

The following does not compile as an expression is passed to `pin!`.

```compile_fail
async fn my_async_fn() {
    // async logic here
}

#[tokio::main]
async fn main() {
    let mut future = pin!(my_async_fn());
    (&mut future).await;
}
```

### tokio::pin (macro) › Examples

Using with select:

```
use tokio::{pin, select};
use tokio_stream::{self as stream, StreamExt};

async fn my_async_fn() {
    // async logic here
}

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let mut stream = stream::iter(vec![1, 2, 3, 4]);

let future = my_async_fn();
pin!(future);

loop {
    select! {
        _ = &mut future => {
            // Stop looping `future` will be polled after completion
            break;
        }
        Some(val) = stream.next() => {
            println!("got value = {}", val);
        }
    }
}
# }
```

Because assigning to a variable followed by pinning is common, there is also
a variant of the macro that supports doing both in one go.

```
use tokio::{pin, select};

async fn my_async_fn() {
    // async logic here
}

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
pin! {
    let future1 = my_async_fn();
    let future2 = my_async_fn();
}

select! {
    _ = &mut future1 => {}
    _ = &mut future2 => {}
}
# }
```

## tokio::pipe (function)

Represents the `SIGPIPE` signal.

On Unix systems this signal is sent when the process attempts to write
to a pipe which has no reader. By default, the process is terminated by
this signal.

## tokio::pipe_mode (function)

The pipe mode.

The default pipe mode is [`PipeMode::Byte`]. See [`PipeMode`] for
documentation of what each mode means.

## tokio::pipe_mode (function)

The pipe mode.

The default pipe mode is [`PipeMode::Byte`]. See [`PipeMode`] for
documentation of what each mode means.

This corresponds to specifying `PIPE_TYPE_` and `PIPE_READMODE_` in  [`dwPipeMode`].

[`dwPipeMode`]: https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createnamedpipea

## tokio::poll_accept (function)

Polls to accept a new incoming connection to this listener.

If there is no connection to accept, `Poll::Pending` is returned and the
current task will be notified by a waker.  Note that on multiple calls
to `poll_accept`, only the `Waker` from the `Context` passed to the most
recent call is scheduled to receive a wakeup.

## tokio::poll_accept (function)

Polls to accept a new incoming connection to this listener.

If there is no connection to accept, `Poll::Pending` is returned and the
current task will be notified by a waker.  Note that on multiple calls
to `poll_accept`, only the `Waker` from the `Context` passed to the most
recent call is scheduled to receive a wakeup.

## tokio::poll_closed (function)

Checks whether the `oneshot` channel has been closed, and if not, schedules the
`Waker` in the provided `Context` to receive a notification when the channel is
closed.

A [`Receiver`] is closed by either calling [`close`] explicitly, or when the
[`Receiver`] value is dropped.

Note that on multiple calls to poll, only the `Waker` from the `Context` passed
to the most recent call will be scheduled to receive a wakeup.

[`Receiver`]: struct@crate::sync::oneshot::Receiver
[`close`]: fn@crate::sync::oneshot::Receiver::close

### tokio::poll_closed (function) › Return value

This function returns:

 * `Poll::Pending` if the channel is still open.
 * `Poll::Ready(())` if the channel is closed.

### tokio::poll_closed (function) › Examples

```
use tokio::sync::oneshot;

use std::future::poll_fn;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (mut tx, mut rx) = oneshot::channel::<()>();

tokio::spawn(async move {
    rx.close();
});

poll_fn(|cx| tx.poll_closed(cx)).await;

println!("the receiver dropped");
# }
```

## tokio::poll_complete (function)

Waits for a seek operation to complete.

If the seek operation completed successfully, this method returns the
new position from the start of the stream. That position can be used
later with [`SeekFrom::Start`].

The position returned by calling this method can only be relied on right
after `start_seek`. If you have changed the position by e.g. reading or
writing since calling `start_seek`, then it is unspecified whether the
returned position takes that position change into account. Similarly, if
`start_seek` has never been called, then it is unspecified whether
`poll_complete` returns the actual position or some other placeholder
value (such as 0).

### tokio::poll_complete (function) › Errors

Seeking to a negative offset is considered an error.

## tokio::poll_fill_buf (function)

Attempts to return the contents of the internal buffer, filling it with more data
from the inner reader if it is empty.

On success, returns `Poll::Ready(Ok(buf))`.

If no data is available for reading, the method returns
`Poll::Pending` and arranges for the current task (via
`cx.waker().wake_by_ref()`) to receive a notification when the object becomes
readable or is closed.

This function is a lower-level call. It needs to be paired with the
[`consume`] method to function properly. When calling this
method, none of the contents will be "read" in the sense that later
calling [`poll_read`] may return the same contents. As such, [`consume`] must
be called with the number of bytes that are consumed from this buffer to
ensure that the bytes are never returned twice.

An empty buffer returned indicates that the stream has reached EOF.

[`poll_read`]: AsyncRead::poll_read
[`consume`]: AsyncBufRead::consume

## tokio::poll_flush (function)

Attempts to flush the object, ensuring that any buffered data reach
their destination.

On success, returns `Poll::Ready(Ok(()))`.

If flushing cannot immediately complete, this method returns
`Poll::Pending` and arranges for the current task (via
`cx.waker()`) to receive a notification when the object can make
progress towards flushing.

## tokio::poll_join_next (function)

Polls for one of the tasks in the set to complete.

If this returns `Poll::Ready(Some(_))`, then the task that completed is removed from the set.

When the method returns `Poll::Pending`, the `Waker` in the provided `Context` is scheduled
to receive a wakeup when a task in the `JoinSet` completes. Note that on multiple calls to
`poll_join_next`, only the `Waker` from the `Context` passed to the most recent call is
scheduled to receive a wakeup.

### tokio::poll_join_next (function) › Returns

This function returns:

 * `Poll::Pending` if the `JoinSet` is not empty but there is no task whose output is
   available right now.
 * `Poll::Ready(Some(Ok(value)))` if one of the tasks in this `JoinSet` has completed.
   The `value` is the return value of one of the tasks that completed.
 * `Poll::Ready(Some(Err(err)))` if one of the tasks in this `JoinSet` has panicked or been
   aborted. The `err` is the `JoinError` from the panicked/aborted task.
 * `Poll::Ready(None)` if the `JoinSet` is empty.

Note that this method may return `Poll::Pending` even if one of the tasks has completed.
This can happen if the [coop budget] is reached.

[coop budget]: crate::task::coop#cooperative-scheduling

## tokio::poll_join_next_with_id (function)

Polls for one of the tasks in the set to complete.

If this returns `Poll::Ready(Some(_))`, then the task that completed is removed from the set.

When the method returns `Poll::Pending`, the `Waker` in the provided `Context` is scheduled
to receive a wakeup when a task in the `JoinSet` completes. Note that on multiple calls to
`poll_join_next`, only the `Waker` from the `Context` passed to the most recent call is
scheduled to receive a wakeup.

### tokio::poll_join_next_with_id (function) › Returns

This function returns:

 * `Poll::Pending` if the `JoinSet` is not empty but there is no task whose output is
   available right now.
 * `Poll::Ready(Some(Ok((id, value))))` if one of the tasks in this `JoinSet` has completed.
   The `value` is the return value of one of the tasks that completed, and
   `id` is the [task ID] of that task.
 * `Poll::Ready(Some(Err(err)))` if one of the tasks in this `JoinSet` has panicked or been
   aborted. The `err` is the `JoinError` from the panicked/aborted task.
 * `Poll::Ready(None)` if the `JoinSet` is empty.

Note that this method may return `Poll::Pending` even if one of the tasks has completed.
This can happen if the [coop budget] is reached.

[coop budget]: crate::task::coop#cooperative-scheduling
[task ID]: crate::task::Id

## tokio::poll_next_entry (function)

Polls for the next directory entry in the stream.

This method returns:

 * `Poll::Pending` if the next directory entry is not yet available.
 * `Poll::Ready(Ok(Some(entry)))` if the next directory entry is available.
 * `Poll::Ready(Ok(None))` if there are no more directory entries in this
   stream.
 * `Poll::Ready(Err(err))` if an IO error occurred while reading the next
   directory entry.

When the method returns `Poll::Pending`, the `Waker` in the provided
`Context` is scheduled to receive a wakeup when the next directory entry
becomes available on the underlying IO resource.

Note that on multiple calls to `poll_next_entry`, only the `Waker` from
the `Context` passed to the most recent call is scheduled to receive a
wakeup.

## tokio::poll_next_line (function)

Polls for the next line in the stream.

This method returns:

 * `Poll::Pending` if the next line is not yet available.
 * `Poll::Ready(Ok(Some(line)))` if the next line is available.
 * `Poll::Ready(Ok(None))` if there are no more lines in this stream.
 * `Poll::Ready(Err(err))` if an IO error occurred while reading the next line.

When the method returns `Poll::Pending`, the `Waker` in the provided
`Context` is scheduled to receive a wakeup when more bytes become
available on the underlying IO resource.  Note that on multiple calls to
`poll_next_line`, only the `Waker` from the `Context` passed to the most
recent call is scheduled to receive a wakeup.

## tokio::poll_next_segment (function)

Polls for the next segment in the stream.

This method returns:

 * `Poll::Pending` if the next segment is not yet available.
 * `Poll::Ready(Ok(Some(segment)))` if the next segment is available.
 * `Poll::Ready(Ok(None))` if there are no more segments in this stream.
 * `Poll::Ready(Err(err))` if an IO error occurred while reading the
   next segment.

When the method returns `Poll::Pending`, the `Waker` in the provided
`Context` is scheduled to receive a wakeup when more bytes become
available on the underlying IO resource.

Note that on multiple calls to `poll_next_segment`, only the `Waker`
from the `Context` passed to the most recent call is scheduled to
receive a wakeup.

## tokio::poll_peek (function)

Attempt to receive data on the socket, without removing that data from
the queue, registering the current task for wakeup if data is not yet
available.

Note that on multiple calls to `poll_peek` or `poll_read`, only the
`Waker` from the `Context` passed to the most recent call is scheduled
to receive a wakeup.

See the [`TcpStream::poll_peek`] level documentation for more details.

### tokio::poll_peek (function) › Examples

```no_run
use tokio::io::{self, ReadBuf};
use tokio::net::TcpStream;

use std::future::poll_fn;

#[tokio::main]
async fn main() -> io::Result<()> {
    let stream = TcpStream::connect("127.0.0.1:8000").await?;
    let (mut read_half, _) = stream.into_split();
    let mut buf = [0; 10];
    let mut buf = ReadBuf::new(&mut buf);

    poll_fn(|cx| {
        read_half.poll_peek(cx, &mut buf)
    }).await?;

    Ok(())
}
```

[`TcpStream::poll_peek`]: TcpStream::poll_peek

## tokio::poll_peek (function)

Attempts to receive data on the socket, without removing that data from
the queue, registering the current task for wakeup if data is not yet
available.

Note that on multiple calls to `poll_peek` or `poll_read`, only the
`Waker` from the `Context` passed to the most recent call is scheduled
to receive a wakeup.

See the [`TcpStream::poll_peek`] level documentation for more details.

### tokio::poll_peek (function) › Examples

```no_run
use tokio::io::{self, ReadBuf};
use tokio::net::TcpStream;

use std::future::poll_fn;

#[tokio::main]
async fn main() -> io::Result<()> {
    let mut stream = TcpStream::connect("127.0.0.1:8000").await?;
    let (mut read_half, _) = stream.split();
    let mut buf = [0; 10];
    let mut buf = ReadBuf::new(&mut buf);

    poll_fn(|cx| {
        read_half.poll_peek(cx, &mut buf)
    }).await?;

    Ok(())
}
```

[`TcpStream::poll_peek`]: TcpStream::poll_peek

## tokio::poll_peek (function)

Attempts to receive data on the socket, without removing that data from
the queue, registering the current task for wakeup if data is not yet
available.

Note that on multiple calls to `poll_peek`, `poll_read` or
`poll_read_ready`, only the `Waker` from the `Context` passed to the
most recent call is scheduled to receive a wakeup. (However,
`poll_write` retains a second, independent waker.)

### tokio::poll_peek (function) › Return value

The function returns:

* `Poll::Pending` if data is not yet available.
* `Poll::Ready(Ok(n))` if data is available. `n` is the number of bytes peeked.
* `Poll::Ready(Err(e))` if an error is encountered.

### tokio::poll_peek (function) › Errors

This function may encounter any standard I/O error except `WouldBlock`.

### tokio::poll_peek (function) › Examples

```no_run
use tokio::io::{self, ReadBuf};
use tokio::net::TcpStream;

use std::future::poll_fn;

#[tokio::main]
async fn main() -> io::Result<()> {
    let stream = TcpStream::connect("127.0.0.1:8000").await?;
    let mut buf = [0; 10];
    let mut buf = ReadBuf::new(&mut buf);

    poll_fn(|cx| {
        stream.poll_peek(cx, &mut buf)
    }).await?;

    Ok(())
}
```

## tokio::poll_peek (function)

Receives data from the connected address, without removing it from the input queue.

### tokio::poll_peek (function) › Notes

Note that on multiple calls to a `poll_*` method in the `recv` direction, only the
`Waker` from the `Context` passed to the most recent call will be scheduled to
receive a wakeup

On Windows, if the data is larger than the buffer specified, the buffer
is filled with the first part of the data, and peek returns the error
`WSAEMSGSIZE(10040)`. The excess data is lost.
Make sure to always use a sufficiently large buffer to hold the
maximum UDP packet size, which can be up to 65536 bytes in size.

MacOS will return an error if you pass a zero-sized buffer.

If you're merely interested in learning the sender of the data at the head of the queue,
try [`poll_peek_sender`].

Note that the socket address **cannot** be implicitly trusted, because it is relatively
trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
Because UDP is stateless and does not validate the origin of a packet,
the attacker does not need to be able to intercept traffic in order to interfere.
It is important to be aware of this when designing your application-level protocol.

### tokio::poll_peek (function) › Return value

The function returns:

* `Poll::Pending` if the socket is not ready to read
* `Poll::Ready(Ok(()))` reads data into `ReadBuf` if the socket is ready
* `Poll::Ready(Err(e))` if an error is encountered.

### tokio::poll_peek (function) › Errors

This function may encounter any standard I/O error except `WouldBlock`.

[`poll_peek_sender`]: method@Self::poll_peek_sender
[packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection

## tokio::poll_peek_from (function)

Receives data from the socket, without removing it from the input queue.
On success, returns the sending address of the datagram.

### tokio::poll_peek_from (function) › Notes

Note that on multiple calls to a `poll_*` method in the `recv` direction, only the
`Waker` from the `Context` passed to the most recent call will be scheduled to
receive a wakeup

On Windows, if the data is larger than the buffer specified, the buffer
is filled with the first part of the data, and peek returns the error
`WSAEMSGSIZE(10040)`. The excess data is lost.
Make sure to always use a sufficiently large buffer to hold the
maximum UDP packet size, which can be up to 65536 bytes in size.

MacOS will return an error if you pass a zero-sized buffer.

If you're merely interested in learning the sender of the data at the head of the queue,
try [`poll_peek_sender`].

Note that the socket address **cannot** be implicitly trusted, because it is relatively
trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
Because UDP is stateless and does not validate the origin of a packet,
the attacker does not need to be able to intercept traffic in order to interfere.
It is important to be aware of this when designing your application-level protocol.

### tokio::poll_peek_from (function) › Return value

The function returns:

* `Poll::Pending` if the socket is not ready to read
* `Poll::Ready(Ok(addr))` reads data from `addr` into `ReadBuf` if the socket is ready
* `Poll::Ready(Err(e))` if an error is encountered.

### tokio::poll_peek_from (function) › Errors

This function may encounter any standard I/O error except `WouldBlock`.

[`poll_peek_sender`]: method@Self::poll_peek_sender
[packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection

## tokio::poll_peek_sender (function)

Retrieve the sender of the data at the head of the input queue,
scheduling a wakeup if empty.

This is equivalent to calling [`poll_peek_from`] with a zero-sized buffer,
but suppresses the `WSAEMSGSIZE` error on Windows and the "invalid argument" error on macOS.

### tokio::poll_peek_sender (function) › Notes

Note that on multiple calls to a `poll_*` method in the `recv` direction, only the
`Waker` from the `Context` passed to the most recent call will be scheduled to
receive a wakeup.

Note that the socket address **cannot** be implicitly trusted, because it is relatively
trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
Because UDP is stateless and does not validate the origin of a packet,
the attacker does not need to be able to intercept traffic in order to interfere.
It is important to be aware of this when designing your application-level protocol.

[`poll_peek_from`]: method@Self::poll_peek_from
[packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection

## tokio::poll_read (function)

Attempts to read from the `AsyncRead` into `buf`.

On success, returns `Poll::Ready(Ok(()))` and places data in the
unfilled portion of `buf`. If no data was read (`buf.filled().len()` is
unchanged), it implies that EOF has been reached, or the output buffer
had zero capacity (i.e. `buf.remaining()` == 0).

If no data is available for reading, the method returns `Poll::Pending`
and arranges for the current task (via `cx.waker()`) to receive a
notification when the object becomes readable or is closed.

## tokio::poll_read_ready (function)

Polls for read readiness.

If the file descriptor is not currently ready for reading, this method
will store a clone of the [`Waker`] from the provided [`Context`]. When the
file descriptor becomes ready for reading, [`Waker::wake`] will be called.

Note that on multiple calls to [`poll_read_ready`] or
[`poll_read_ready_mut`], only the `Waker` from the `Context` passed to the
most recent call is scheduled to receive a wakeup. (However,
[`poll_write_ready`] retains a second, independent waker).

This method is intended for cases where creating and pinning a future
via [`readable`] is not feasible. Where possible, using [`readable`] is
preferred, as this supports polling from multiple tasks at once.

This method takes `&self`, so it is possible to call this method
concurrently with other methods on this struct. This method only
provides shared access to the inner IO resource when handling the
[`AsyncFdReadyGuard`].

[`poll_read_ready`]: method@Self::poll_read_ready
[`poll_read_ready_mut`]: method@Self::poll_read_ready_mut
[`poll_write_ready`]: method@Self::poll_write_ready
[`readable`]: method@Self::readable
[`Context`]: struct@std::task::Context
[`Waker`]: struct@std::task::Waker
[`Waker::wake`]: method@std::task::Waker::wake

## tokio::poll_read_ready (function)

Polls for read readiness.

If the pipe is not currently ready for reading, this method will
store a clone of the `Waker` from the provided `Context`. When the pipe
becomes ready for reading, `Waker::wake` will be called on the waker.

Note that on multiple calls to `poll_read_ready` or `poll_read`, only
the `Waker` from the `Context` passed to the most recent call is
scheduled to receive a wakeup.

This function is intended for cases where creating and pinning a future
via [`readable`] is not feasible. Where possible, using [`readable`] is
preferred, as this supports polling from multiple tasks at once.

[`readable`]: Self::readable

### tokio::poll_read_ready (function) › Return value

The function returns:

* `Poll::Pending` if the pipe is not ready for reading.
* `Poll::Ready(Ok(()))` if the pipe is ready for reading.
* `Poll::Ready(Err(e))` if an error is encountered.

### tokio::poll_read_ready (function) › Errors

This function may encounter any standard I/O error except `WouldBlock`.

## tokio::poll_read_ready (function)

Polls for read readiness.

If the pipe is not currently ready for reading, this method will
store a clone of the `Waker` from the provided `Context`. When the pipe
becomes ready for reading, `Waker::wake` will be called on the waker.

Note that on multiple calls to `poll_read_ready` or `poll_read`, only
the `Waker` from the `Context` passed to the most recent call is
scheduled to receive a wakeup. (However, `poll_write_ready` retains a
second, independent waker.)

This function is intended for cases where creating and pinning a future
via [`readable`] is not feasible. Where possible, using [`readable`] is
preferred, as this supports polling from multiple tasks at once.

### tokio::poll_read_ready (function) › Return value

The function returns:

* `Poll::Pending` if the pipe is not ready for reading.
* `Poll::Ready(Ok(()))` if the pipe is ready for reading.
* `Poll::Ready(Err(e))` if an error is encountered.

### tokio::poll_read_ready (function) › Errors

This function may encounter any standard I/O error except `WouldBlock`.

[`readable`]: method@Self::readable

## tokio::poll_read_ready (function)

Polls for read readiness.

If the pipe is not currently ready for reading, this method will
store a clone of the `Waker` from the provided `Context`. When the pipe
becomes ready for reading, `Waker::wake` will be called on the waker.

Note that on multiple calls to `poll_read_ready` or `poll_read`, only
the `Waker` from the `Context` passed to the most recent call is
scheduled to receive a wakeup. (However, `poll_write_ready` retains a
second, independent waker.)

This function is intended for cases where creating and pinning a future
via [`readable`] is not feasible. Where possible, using [`readable`] is
preferred, as this supports polling from multiple tasks at once.

### tokio::poll_read_ready (function) › Return value

The function returns:

* `Poll::Pending` if the pipe is not ready for reading.
* `Poll::Ready(Ok(()))` if the pipe is ready for reading.
* `Poll::Ready(Err(e))` if an error is encountered.

### tokio::poll_read_ready (function) › Errors

This function may encounter any standard I/O error except `WouldBlock`.

[`readable`]: method@Self::readable

## tokio::poll_read_ready (function)

Polls for read readiness.

If the tcp stream is not currently ready for reading, this method will
store a clone of the `Waker` from the provided `Context`. When the tcp
stream becomes ready for reading, `Waker::wake` will be called on the
waker.

Note that on multiple calls to `poll_read_ready`, `poll_read` or
`poll_peek`, only the `Waker` from the `Context` passed to the most
recent call is scheduled to receive a wakeup. (However,
`poll_write_ready` retains a second, independent waker.)

This function is intended for cases where creating and pinning a future
via [`readable`] is not feasible. Where possible, using [`readable`] is
preferred, as this supports polling from multiple tasks at once.

### tokio::poll_read_ready (function) › Return value

The function returns:

* `Poll::Pending` if the tcp stream is not ready for reading.
* `Poll::Ready(Ok(()))` if the tcp stream is ready for reading.
* `Poll::Ready(Err(e))` if an error is encountered.

### tokio::poll_read_ready (function) › Errors

This function may encounter any standard I/O error except `WouldBlock`.

[`readable`]: method@Self::readable

## tokio::poll_read_ready (function)

Polls for read readiness.

If the unix stream is not currently ready for reading, this method will
store a clone of the `Waker` from the provided `Context`. When the unix
stream becomes ready for reading, `Waker::wake` will be called on the
waker.

Note that on multiple calls to `poll_read_ready` or `poll_read`, only
the `Waker` from the `Context` passed to the most recent call is
scheduled to receive a wakeup. (However, `poll_write_ready` retains a
second, independent waker.)

This function is intended for cases where creating and pinning a future
via [`readable`] is not feasible. Where possible, using [`readable`] is
preferred, as this supports polling from multiple tasks at once.

### tokio::poll_read_ready (function) › Return value

The function returns:

* `Poll::Pending` if the unix stream is not ready for reading.
* `Poll::Ready(Ok(()))` if the unix stream is ready for reading.
* `Poll::Ready(Err(e))` if an error is encountered.

### tokio::poll_read_ready (function) › Errors

This function may encounter any standard I/O error except `WouldBlock`.

[`readable`]: method@Self::readable

## tokio::poll_read_ready_mut (function)

Polls for read readiness.

If the file descriptor is not currently ready for reading, this method
will store a clone of the [`Waker`] from the provided [`Context`]. When the
file descriptor becomes ready for reading, [`Waker::wake`] will be called.

Note that on multiple calls to [`poll_read_ready`] or
[`poll_read_ready_mut`], only the `Waker` from the `Context` passed to the
most recent call is scheduled to receive a wakeup. (However,
[`poll_write_ready`] retains a second, independent waker).

This method is intended for cases where creating and pinning a future
via [`readable`] is not feasible. Where possible, using [`readable`] is
preferred, as this supports polling from multiple tasks at once.

This method takes `&mut self`, so it is possible to access the inner IO
resource mutably when handling the [`AsyncFdReadyMutGuard`].

[`poll_read_ready`]: method@Self::poll_read_ready
[`poll_read_ready_mut`]: method@Self::poll_read_ready_mut
[`poll_write_ready`]: method@Self::poll_write_ready
[`readable`]: method@Self::readable
[`Context`]: struct@std::task::Context
[`Waker`]: struct@std::task::Waker
[`Waker::wake`]: method@std::task::Waker::wake

## tokio::poll_ready (function)

Polls for readiness.  Either AIO or LIO counts.

This method returns:
 * `Poll::Pending` if the underlying operation is not complete, whether
    or not it completed successfully.  This will be true if the OS is
    still processing it, or if it has not yet been submitted to the OS.
 * `Poll::Ready(Ok(_))` if the underlying operation is complete.
 * `Poll::Ready(Err(_))` if the reactor has been shutdown.  This does
    _not_ indicate that the underlying operation encountered an error.

When the method returns `Poll::Pending`, the `Waker` in the provided `Context`
is scheduled to receive a wakeup when the underlying operation
completes. Note that on multiple calls to `poll_ready`, only the `Waker` from the
`Context` passed to the most recent call is scheduled to receive a wakeup.

## tokio::poll_recv (function)

Attempts to receive a single datagram message on the socket from the remote
address to which it is `connect`ed.

The [`connect`] method will connect this socket to a remote address. This method
resolves to an error if the socket is not connected.

Note that on multiple calls to a `poll_*` method in the `recv` direction, only the
`Waker` from the `Context` passed to the most recent call will be scheduled to
receive a wakeup.

### tokio::poll_recv (function) › Return value

The function returns:

* `Poll::Pending` if the socket is not ready to read
* `Poll::Ready(Ok(()))` reads data `ReadBuf` if the socket is ready
* `Poll::Ready(Err(e))` if an error is encountered.

### tokio::poll_recv (function) › Errors

This function may encounter any standard I/O error except `WouldBlock`.

[`connect`]: method@Self::connect

## tokio::poll_recv (function)

Polls to receive the next message on this channel.

This method returns:

 * `Poll::Pending` if no messages are available but the channel is not
   closed, or if a spurious failure happens.
 * `Poll::Ready(Some(message))` if a message is available.
 * `Poll::Ready(None)` if the channel has been closed and all messages
   sent before it was closed have been received.

When the method returns `Poll::Pending`, the `Waker` in the provided
`Context` is scheduled to receive a wakeup when a message is sent on any
receiver, or when the channel is closed.  Note that on multiple calls to
`poll_recv` or `poll_recv_many`, only the `Waker` from the `Context`
passed to the most recent call is scheduled to receive a wakeup.

If this method returns `Poll::Pending` due to a spurious failure, then
the `Waker` will be notified when the situation causing the spurious
failure has been resolved. Note that receiving such a wakeup does not
guarantee that the next call will succeed — it could fail with another
spurious failure.

## tokio::poll_recv (function)

Polls to receive the next message on this channel.

This method returns:

 * `Poll::Pending` if no messages are available but the channel is not
   closed, or if a spurious failure happens.
 * `Poll::Ready(Some(message))` if a message is available.
 * `Poll::Ready(None)` if the channel has been closed and all messages
   sent before it was closed have been received.

When the method returns `Poll::Pending`, the `Waker` in the provided
`Context` is scheduled to receive a wakeup when a message is sent on any
receiver, or when the channel is closed.  Note that on multiple calls to
`poll_recv` or `poll_recv_many`, only the `Waker` from the `Context`
passed to the most recent call is scheduled to receive a wakeup.

If this method returns `Poll::Pending` due to a spurious failure, then
the `Waker` will be notified when the situation causing the spurious
failure has been resolved. Note that receiving such a wakeup does not
guarantee that the next call will succeed — it could fail with another
spurious failure.

## tokio::poll_recv (function)

Polls to receive the next signal notification event, outside of an
`async` context.

Although this returns `Option<()>`, it will never actually return `None`.
This was accidentally exposed and would be a breaking change to be removed.

### tokio::poll_recv (function) › Examples

Polling from a manually implemented future

```rust,no_run
use std::pin::Pin;
use std::future::Future;
use std::task::{Context, Poll};
use tokio::signal::unix::Signal;

struct MyFuture {
    signal: Signal,
}

impl Future for MyFuture {
    type Output = Option<()>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        println!("polling MyFuture");
        self.signal.poll_recv(cx)
    }
}
```

## tokio::poll_recv (function)

Polls to receive the next signal notification event, outside of an
`async` context.

Although this returns `Option<()>`, it will never actually return `None`.
This was accidentally exposed and would be a breaking change to be removed.

### tokio::poll_recv (function) › Examples

Polling from a manually implemented future

```rust,no_run
use std::pin::Pin;
use std::future::Future;
use std::task::{Context, Poll};
use tokio::signal::windows::CtrlBreak;

struct MyFuture {
    ctrl_break: CtrlBreak,
}

impl Future for MyFuture {
    type Output = Option<()>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        println!("polling MyFuture");
        self.ctrl_break.poll_recv(cx)
    }
}
```

## tokio::poll_recv (function)

Polls to receive the next signal notification event, outside of an
`async` context.

Although this returns `Option<()>`, it will never actually return `None`.
This was accidentally exposed and would be a breaking change to be removed.

### tokio::poll_recv (function) › Examples

Polling from a manually implemented future

```rust,no_run
use std::pin::Pin;
use std::future::Future;
use std::task::{Context, Poll};
use tokio::signal::windows::CtrlC;

struct MyFuture {
    ctrl_c: CtrlC,
}

impl Future for MyFuture {
    type Output = Option<()>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        println!("polling MyFuture");
        self.ctrl_c.poll_recv(cx)
    }
}
```

## tokio::poll_recv (function)

Polls to receive the next signal notification event, outside of an
`async` context.

Although this returns `Option<()>`, it will never actually return `None`.
This was accidentally exposed and would be a breaking change to be removed.

### tokio::poll_recv (function) › Examples

Polling from a manually implemented future

```rust,no_run
use std::pin::Pin;
use std::future::Future;
use std::task::{Context, Poll};
use tokio::signal::windows::CtrlClose;

struct MyFuture {
    ctrl_close: CtrlClose,
}

impl Future for MyFuture {
    type Output = Option<()>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        println!("polling MyFuture");
        self.ctrl_close.poll_recv(cx)
    }
}
```

## tokio::poll_recv (function)

Polls to receive the next signal notification event, outside of an
`async` context.

Although this returns `Option<()>`, it will never actually return `None`.
This was accidentally exposed and would be a breaking change to be removed.

### tokio::poll_recv (function) › Examples

Polling from a manually implemented future

```rust,no_run
use std::pin::Pin;
use std::future::Future;
use std::task::{Context, Poll};
use tokio::signal::windows::CtrlLogoff;

struct MyFuture {
    ctrl_logoff: CtrlLogoff,
}

impl Future for MyFuture {
    type Output = Option<()>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        println!("polling MyFuture");
        self.ctrl_logoff.poll_recv(cx)
    }
}
```

## tokio::poll_recv (function)

Polls to receive the next signal notification event, outside of an
`async` context.

Although this returns `Option<()>`, it will never actually return `None`.
This was accidentally exposed and would be a breaking change to be removed.

### tokio::poll_recv (function) › Examples

Polling from a manually implemented future

```rust,no_run
use std::pin::Pin;
use std::future::Future;
use std::task::{Context, Poll};
use tokio::signal::windows::CtrlShutdown;

struct MyFuture {
    ctrl_shutdown: CtrlShutdown,
}

impl Future for MyFuture {
    type Output = Option<()>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        println!("polling MyFuture");
        self.ctrl_shutdown.poll_recv(cx)
    }
}
```

## tokio::poll_recv_from (function)

Attempts to receive a single datagram on the socket.

Note that on multiple calls to a `poll_*` method in the `recv` direction, only the
`Waker` from the `Context` passed to the most recent call will be scheduled to
receive a wakeup.

### tokio::poll_recv_from (function) › Return value

The function returns:

* `Poll::Pending` if the socket is not ready to read
* `Poll::Ready(Ok(addr))` reads data from `addr` into `ReadBuf` if the socket is ready
* `Poll::Ready(Err(e))` if an error is encountered.

### tokio::poll_recv_from (function) › Errors

This function may encounter any standard I/O error except `WouldBlock`.

### tokio::poll_recv_from (function) › Notes
Note that the socket address **cannot** be implicitly trusted, because it is relatively
trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
Because UDP is stateless and does not validate the origin of a packet,
the attacker does not need to be able to intercept traffic in order to interfere.
It is important to be aware of this when designing your application-level protocol.

[packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection

## tokio::poll_recv_many (function)

Polls to receive multiple messages on this channel, extending the provided buffer.

This method returns:
* `Poll::Pending` if no messages are available but the channel is not closed, or if a
  spurious failure happens.
* `Poll::Ready(count)` where `count` is the number of messages successfully received and
  stored in `buffer`. This can be less than, or equal to, `limit`.
* `Poll::Ready(0)` if `limit` is set to zero or when the channel is closed.

When the method returns `Poll::Pending`, the `Waker` in the provided
`Context` is scheduled to receive a wakeup when a message is sent on any
receiver, or when the channel is closed.  Note that on multiple calls to
`poll_recv` or `poll_recv_many`, only the `Waker` from the `Context`
passed to the most recent call is scheduled to receive a wakeup.

Note that this method does not guarantee that exactly `limit` messages
are received. Rather, if at least one message is available, it returns
as many messages as it can up to the given limit. This method returns
zero only if the channel is closed (or if `limit` is zero).

### tokio::poll_recv_many (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use std::task::{Context, Poll};
use std::pin::Pin;
use tokio::sync::mpsc;
use futures::Future;

struct MyReceiverFuture<'a> {
    receiver: mpsc::UnboundedReceiver<i32>,
    buffer: &'a mut Vec<i32>,
    limit: usize,
}

impl<'a> Future for MyReceiverFuture<'a> {
    type Output = usize; // Number of messages received

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let MyReceiverFuture { receiver, buffer, limit } = &mut *self;

        // Now `receiver` and `buffer` are mutable references, and `limit` is copied
        match receiver.poll_recv_many(cx, *buffer, *limit) {
            Poll::Pending => Poll::Pending,
            Poll::Ready(count) => Poll::Ready(count),
        }
    }
}

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, rx) = mpsc::unbounded_channel::<i32>();
let mut buffer = Vec::new();

let my_receiver_future = MyReceiverFuture {
    receiver: rx,
    buffer: &mut buffer,
    limit: 3,
};

for i in 0..10 {
    tx.send(i).expect("Unable to send integer");
}

let count = my_receiver_future.await;
assert_eq!(count, 3);
assert_eq!(buffer, vec![0,1,2])
# }
# }
```

## tokio::poll_recv_many (function)

Polls to receive multiple messages on this channel, extending the provided buffer.

This method returns:
* `Poll::Pending` if no messages are available but the channel is not closed, or if a
  spurious failure happens.
* `Poll::Ready(count)` where `count` is the number of messages successfully received and
  stored in `buffer`. This can be less than, or equal to, `limit`.
* `Poll::Ready(0)` if `limit` is set to zero or when the channel is closed.

When the method returns `Poll::Pending`, the `Waker` in the provided
`Context` is scheduled to receive a wakeup when a message is sent on any
receiver, or when the channel is closed.  Note that on multiple calls to
`poll_recv` or `poll_recv_many`, only the `Waker` from the `Context`
passed to the most recent call is scheduled to receive a wakeup.

Note that this method does not guarantee that exactly `limit` messages
are received. Rather, if at least one message is available, it returns
as many messages as it can up to the given limit. This method returns
zero only if the channel is closed (or if `limit` is zero).

### tokio::poll_recv_many (function) › Examples

```
use std::task::{Context, Poll};
use std::pin::Pin;
use tokio::sync::mpsc;
use futures::Future;

struct MyReceiverFuture<'a> {
    receiver: mpsc::Receiver<i32>,
    buffer: &'a mut Vec<i32>,
    limit: usize,
}

impl<'a> Future for MyReceiverFuture<'a> {
    type Output = usize; // Number of messages received

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let MyReceiverFuture { receiver, buffer, limit } = &mut *self;

        // Now `receiver` and `buffer` are mutable references, and `limit` is copied
        match receiver.poll_recv_many(cx, *buffer, *limit) {
            Poll::Pending => Poll::Pending,
            Poll::Ready(count) => Poll::Ready(count),
        }
    }
}

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, rx) = mpsc::channel(32);
let mut buffer = Vec::new();

let my_receiver_future = MyReceiverFuture {
    receiver: rx,
    buffer: &mut buffer,
    limit: 3,
};

for i in 0..10 {
    tx.send(i).await.unwrap();
}

let count = my_receiver_future.await;
assert_eq!(count, 3);
assert_eq!(buffer, vec![0,1,2])
# }
```

## tokio::poll_recv_ready (function)

Polls for read/receive readiness.

If the udp stream is not currently ready for receiving, this method will
store a clone of the `Waker` from the provided `Context`. When the udp
socket becomes ready for reading, `Waker::wake` will be called on the
waker.

Note that on multiple calls to `poll_recv_ready`, `poll_recv` or
`poll_peek`, only the `Waker` from the `Context` passed to the most
recent call is scheduled to receive a wakeup. (However,
`poll_send_ready` retains a second, independent waker.)

This function is intended for cases where creating and pinning a future
via [`readable`] is not feasible. Where possible, using [`readable`] is
preferred, as this supports polling from multiple tasks at once.

### tokio::poll_recv_ready (function) › Return value

The function returns:

* `Poll::Pending` if the udp stream is not ready for reading.
* `Poll::Ready(Ok(()))` if the udp stream is ready for reading.
* `Poll::Ready(Err(e))` if an error is encountered.

### tokio::poll_recv_ready (function) › Errors

This function may encounter any standard I/O error except `WouldBlock`.

[`readable`]: method@Self::readable

## tokio::poll_send (function)

Attempts to send data on the socket to the remote address to which it
was previously `connect`ed.

The [`connect`] method will connect this socket to a remote address.
This method will fail if the socket is not connected.

Note that on multiple calls to a `poll_*` method in the send direction,
only the `Waker` from the `Context` passed to the most recent call will
be scheduled to receive a wakeup.

### tokio::poll_send (function) › Return value

The function returns:

* `Poll::Pending` if the socket is not available to write
* `Poll::Ready(Ok(n))` `n` is the number of bytes sent
* `Poll::Ready(Err(e))` if an error is encountered.

### tokio::poll_send (function) › Errors

This function may encounter any standard I/O error except `WouldBlock`.

[`connect`]: method@Self::connect

## tokio::poll_send_ready (function)

Polls for write/send readiness.

If the udp stream is not currently ready for sending, this method will
store a clone of the `Waker` from the provided `Context`. When the udp
stream becomes ready for sending, `Waker::wake` will be called on the
waker.

Note that on multiple calls to `poll_send_ready` or `poll_send`, only
the `Waker` from the `Context` passed to the most recent call is
scheduled to receive a wakeup. (However, `poll_recv_ready` retains a
second, independent waker.)

This function is intended for cases where creating and pinning a future
via [`writable`] is not feasible. Where possible, using [`writable`] is
preferred, as this supports polling from multiple tasks at once.

### tokio::poll_send_ready (function) › Return value

The function returns:

* `Poll::Pending` if the udp stream is not ready for writing.
* `Poll::Ready(Ok(()))` if the udp stream is ready for writing.
* `Poll::Ready(Err(e))` if an error is encountered.

### tokio::poll_send_ready (function) › Errors

This function may encounter any standard I/O error except `WouldBlock`.

[`writable`]: method@Self::writable

## tokio::poll_send_to (function)

Attempts to send data on the socket to a given address.

Note that on multiple calls to a `poll_*` method in the send direction, only the
`Waker` from the `Context` passed to the most recent call will be scheduled to
receive a wakeup.

### tokio::poll_send_to (function) › Return value

The function returns:

* `Poll::Pending` if the socket is not ready to write
* `Poll::Ready(Ok(n))` `n` is the number of bytes sent.
* `Poll::Ready(Err(e))` if an error is encountered.

### tokio::poll_send_to (function) › Errors

This function may encounter any standard I/O error except `WouldBlock`.

## tokio::poll_shutdown (function)

Initiates or attempts to shut down this writer, returning success when
the I/O connection has completely shut down.

This method is intended to be used for asynchronous shutdown of I/O
connections. For example this is suitable for implementing shutdown of a
TLS connection or calling `TcpStream::shutdown` on a proxied connection.
Protocols sometimes need to flush out final pieces of data or otherwise
perform a graceful shutdown handshake, reading/writing more data as
appropriate. This method is the hook for such protocols to implement the
graceful shutdown logic.

This `shutdown` method is required by implementers of the
`AsyncWrite` trait. Wrappers typically just want to proxy this call
through to the wrapped type, and base types will typically implement
shutdown logic here or just return `Ok(().into())`. Note that if you're
wrapping an underlying `AsyncWrite` a call to `shutdown` implies that
transitively the entire stream has been shut down. After your wrapper's
shutdown logic has been executed you should shut down the underlying
stream.

Invocation of a `shutdown` implies an invocation of `flush`. Once this
method returns `Ready` it implies that a flush successfully happened
before the shutdown happened. That is, callers don't need to call
`flush` before calling `shutdown`. They can rely that by calling
`shutdown` any pending buffered data will be written out.

### tokio::poll_shutdown (function) › Return value

This function returns a `Poll<io::Result<()>>` classified as such:

* `Poll::Ready(Ok(()))` - indicates that the connection was
  successfully shut down and is now safe to deallocate/drop/close
  resources associated with it. This method means that the current task
  will no longer receive any notifications due to this method and the
  I/O object itself is likely no longer usable.

* `Poll::Pending` - indicates that shutdown is initiated but could
  not complete just yet. This may mean that more I/O needs to happen to
  continue this shutdown operation. The current task is scheduled to
  receive a notification when it's otherwise ready to continue the
  shutdown operation. When woken up this method should be called again.

* `Poll::Ready(Err(e))` - indicates a fatal error has happened with shutdown,
  indicating that the shutdown operation did not complete successfully.
  This typically means that the I/O object is no longer usable.

### tokio::poll_shutdown (function) › Errors

This function can return normal I/O errors through `Err`, described
above. Additionally this method may also render the underlying
`Write::write` method no longer usable (e.g. will return errors in the
future). It's recommended that once `shutdown` is called the
`write` method is no longer called.

### tokio::poll_shutdown (function) › Panics

This function will panic if not called within the context of a future's
task.

## tokio::poll_tick (function)

Polls for the next instant in the interval to be reached.

This method can return the following values:

 * `Poll::Pending` if the next instant has not yet been reached.
 * `Poll::Ready(instant)` if the next instant has been reached.

When this method returns `Poll::Pending`, the current task is scheduled
to receive a wakeup when the instant has elapsed. Note that on multiple
calls to `poll_tick`, only the [`Waker`](std::task::Waker) from the
[`Context`] passed to the most recent call is scheduled to receive a
wakeup.

## tokio::poll_time_histogram_bucket_count (function)

Returns the number of times the given worker polled tasks with a poll
duration within the given bucket's range.

Each worker maintains its own histogram and the counts for each bucket
starts at zero when the runtime is created. Each time the worker polls a
task, it tracks the duration the task poll time took and increments the
associated bucket by 1.

Each bucket is a monotonically increasing counter. It is never
decremented or reset to zero.

### tokio::poll_time_histogram_bucket_count (function) › Arguments

`worker` is the index of the worker being queried. The given value must
be between 0 and `num_workers()`. The index uniquely identifies a single
worker and will continue to identify the worker throughout the lifetime
of the runtime instance.

`bucket` is the index of the bucket being queried. The bucket is scoped
to the worker. The range represented by the bucket can be queried by
calling [`poll_time_histogram_bucket_range()`]. Each worker maintains
identical bucket ranges.

### tokio::poll_time_histogram_bucket_count (function) › Panics

The method panics when `worker` represents an invalid worker, i.e. is
greater than or equal to `num_workers()` or if `bucket` represents an
invalid bucket.

### tokio::poll_time_histogram_bucket_count (function) › Examples

```
use tokio::runtime::{self, Handle};

fn main() {
    runtime::Builder::new_current_thread()
        .enable_metrics_poll_time_histogram()
        .build()
        .unwrap()
        .block_on(async {
            let metrics = Handle::current().metrics();
            let buckets = metrics.poll_time_histogram_num_buckets();

            for worker in 0..metrics.num_workers() {
                for i in 0..buckets {
                    let count = metrics.poll_time_histogram_bucket_count(worker, i);
                    println!("Poll count {}", count);
                }
            }
        });
}
```

[`poll_time_histogram_bucket_range()`]: crate::runtime::RuntimeMetrics::poll_time_histogram_bucket_range

## tokio::poll_time_histogram_bucket_range (function)

Returns the range of task poll times tracked by the given bucket.

This value is configured by calling
[`metrics_poll_time_histogram_configuration()`] when building the runtime.

### tokio::poll_time_histogram_bucket_range (function) › Panics

The method panics if `bucket` represents an invalid bucket index, i.e.
is greater than or equal to `poll_time_histogram_num_buckets()`.

### tokio::poll_time_histogram_bucket_range (function) › Examples

```
use tokio::runtime::{self, Handle};

fn main() {
    runtime::Builder::new_current_thread()
        .enable_metrics_poll_time_histogram()
        .build()
        .unwrap()
        .block_on(async {
            let metrics = Handle::current().metrics();
            let buckets = metrics.poll_time_histogram_num_buckets();

            for i in 0..buckets {
                let range = metrics.poll_time_histogram_bucket_range(i);
                println!("Histogram bucket {} range: {:?}", i, range);
            }
        });
}
```

[`metrics_poll_time_histogram_configuration()`]:
    crate::runtime::Builder::metrics_poll_time_histogram_configuration

## tokio::poll_time_histogram_enabled (function)

Returns `true` if the runtime is tracking the distribution of task poll
times.

Task poll times are not instrumented by default as doing so requires
calling [`Instant::now()`] twice per task poll. The feature is enabled
by calling [`enable_metrics_poll_time_histogram()`] when building the
runtime.

### tokio::poll_time_histogram_enabled (function) › Examples

```
use tokio::runtime::{self, Handle};

fn main() {
    runtime::Builder::new_current_thread()
        .enable_metrics_poll_time_histogram()
        .build()
        .unwrap()
        .block_on(async {
            let metrics = Handle::current().metrics();
            let enabled = metrics.poll_time_histogram_enabled();

            println!("Tracking task poll time distribution: {:?}", enabled);
        });
}
```

[`enable_metrics_poll_time_histogram()`]: crate::runtime::Builder::enable_metrics_poll_time_histogram
[`Instant::now()`]: std::time::Instant::now

## tokio::poll_time_histogram_num_buckets (function)

Returns the number of histogram buckets tracking the distribution of
task poll times.

This value is configured by calling
[`metrics_poll_time_histogram_configuration()`] when building the runtime.

### tokio::poll_time_histogram_num_buckets (function) › Examples

```
use tokio::runtime::{self, Handle};

fn main() {
    runtime::Builder::new_current_thread()
        .enable_metrics_poll_time_histogram()
        .build()
        .unwrap()
        .block_on(async {
            let metrics = Handle::current().metrics();
            let buckets = metrics.poll_time_histogram_num_buckets();

            println!("Histogram buckets: {:?}", buckets);
        });
}
```

[`metrics_poll_time_histogram_configuration()`]:
    crate::runtime::Builder::metrics_poll_time_histogram_configuration

## tokio::poll_write (function)

Attempt to write bytes from `buf` into the object.

On success, returns `Poll::Ready(Ok(num_bytes_written))`. If successful,
then it must be guaranteed that `n <= buf.len()`. A return value of `0`
typically means that the underlying object is no longer able to accept
bytes and will likely not be able to in the future as well, or that the
buffer provided is empty.

If the object is not ready for writing, the method returns
`Poll::Pending` and arranges for the current task (via
`cx.waker()`) to receive a notification when the object becomes
writable or is closed.

## tokio::poll_write_ready (function)

Polls for write readiness.

If the file descriptor is not currently ready for writing, this method
will store a clone of the [`Waker`] from the provided [`Context`]. When the
file descriptor becomes ready for writing, [`Waker::wake`] will be called.

Note that on multiple calls to [`poll_write_ready`] or
[`poll_write_ready_mut`], only the `Waker` from the `Context` passed to the
most recent call is scheduled to receive a wakeup. (However,
[`poll_read_ready`] retains a second, independent waker).

This method is intended for cases where creating and pinning a future
via [`writable`] is not feasible. Where possible, using [`writable`] is
preferred, as this supports polling from multiple tasks at once.

This method takes `&self`, so it is possible to call this method
concurrently with other methods on this struct. This method only
provides shared access to the inner IO resource when handling the
[`AsyncFdReadyGuard`].

[`poll_read_ready`]: method@Self::poll_read_ready
[`poll_write_ready`]: method@Self::poll_write_ready
[`poll_write_ready_mut`]: method@Self::poll_write_ready_mut
[`writable`]: method@Self::readable
[`Context`]: struct@std::task::Context
[`Waker`]: struct@std::task::Waker
[`Waker::wake`]: method@std::task::Waker::wake

## tokio::poll_write_ready (function)

Polls for write readiness.

If the pipe is not currently ready for writing, this method will
store a clone of the `Waker` from the provided `Context`. When the pipe
becomes ready for writing, `Waker::wake` will be called on the waker.

Note that on multiple calls to `poll_write_ready` or `poll_write`, only
the `Waker` from the `Context` passed to the most recent call is
scheduled to receive a wakeup.

This function is intended for cases where creating and pinning a future
via [`writable`] is not feasible. Where possible, using [`writable`] is
preferred, as this supports polling from multiple tasks at once.

[`writable`]: Self::writable

### tokio::poll_write_ready (function) › Return value

The function returns:

* `Poll::Pending` if the pipe is not ready for writing.
* `Poll::Ready(Ok(()))` if the pipe is ready for writing.
* `Poll::Ready(Err(e))` if an error is encountered.

### tokio::poll_write_ready (function) › Errors

This function may encounter any standard I/O error except `WouldBlock`.

## tokio::poll_write_ready (function)

Polls for write readiness.

If the pipe is not currently ready for writing, this method will
store a clone of the `Waker` from the provided `Context`. When the pipe
becomes ready for writing, `Waker::wake` will be called on the waker.

Note that on multiple calls to `poll_write_ready` or `poll_write`, only
the `Waker` from the `Context` passed to the most recent call is
scheduled to receive a wakeup. (However, `poll_read_ready` retains a
second, independent waker.)

This function is intended for cases where creating and pinning a future
via [`writable`] is not feasible. Where possible, using [`writable`] is
preferred, as this supports polling from multiple tasks at once.

### tokio::poll_write_ready (function) › Return value

The function returns:

* `Poll::Pending` if the pipe is not ready for writing.
* `Poll::Ready(Ok(()))` if the pipe is ready for writing.
* `Poll::Ready(Err(e))` if an error is encountered.

### tokio::poll_write_ready (function) › Errors

This function may encounter any standard I/O error except `WouldBlock`.

[`writable`]: method@Self::writable

## tokio::poll_write_ready (function)

Polls for write readiness.

If the pipe is not currently ready for writing, this method will
store a clone of the `Waker` from the provided `Context`. When the pipe
becomes ready for writing, `Waker::wake` will be called on the waker.

Note that on multiple calls to `poll_write_ready` or `poll_write`, only
the `Waker` from the `Context` passed to the most recent call is
scheduled to receive a wakeup. (However, `poll_read_ready` retains a
second, independent waker.)

This function is intended for cases where creating and pinning a future
via [`writable`] is not feasible. Where possible, using [`writable`] is
preferred, as this supports polling from multiple tasks at once.

### tokio::poll_write_ready (function) › Return value

The function returns:

* `Poll::Pending` if the pipe is not ready for writing.
* `Poll::Ready(Ok(()))` if the pipe is ready for writing.
* `Poll::Ready(Err(e))` if an error is encountered.

### tokio::poll_write_ready (function) › Errors

This function may encounter any standard I/O error except `WouldBlock`.

[`writable`]: method@Self::writable

## tokio::poll_write_ready (function)

Polls for write readiness.

If the tcp stream is not currently ready for writing, this method will
store a clone of the `Waker` from the provided `Context`. When the tcp
stream becomes ready for writing, `Waker::wake` will be called on the
waker.

Note that on multiple calls to `poll_write_ready` or `poll_write`, only
the `Waker` from the `Context` passed to the most recent call is
scheduled to receive a wakeup. (However, `poll_read_ready` retains a
second, independent waker.)

This function is intended for cases where creating and pinning a future
via [`writable`] is not feasible. Where possible, using [`writable`] is
preferred, as this supports polling from multiple tasks at once.

### tokio::poll_write_ready (function) › Return value

The function returns:

* `Poll::Pending` if the tcp stream is not ready for writing.
* `Poll::Ready(Ok(()))` if the tcp stream is ready for writing.
* `Poll::Ready(Err(e))` if an error is encountered.

### tokio::poll_write_ready (function) › Errors

This function may encounter any standard I/O error except `WouldBlock`.

[`writable`]: method@Self::writable

## tokio::poll_write_ready (function)

Polls for write readiness.

If the unix stream is not currently ready for writing, this method will
store a clone of the `Waker` from the provided `Context`. When the unix
stream becomes ready for writing, `Waker::wake` will be called on the
waker.

Note that on multiple calls to `poll_write_ready` or `poll_write`, only
the `Waker` from the `Context` passed to the most recent call is
scheduled to receive a wakeup. (However, `poll_read_ready` retains a
second, independent waker.)

This function is intended for cases where creating and pinning a future
via [`writable`] is not feasible. Where possible, using [`writable`] is
preferred, as this supports polling from multiple tasks at once.

### tokio::poll_write_ready (function) › Return value

The function returns:

* `Poll::Pending` if the unix stream is not ready for writing.
* `Poll::Ready(Ok(()))` if the unix stream is ready for writing.
* `Poll::Ready(Err(e))` if an error is encountered.

### tokio::poll_write_ready (function) › Errors

This function may encounter any standard I/O error except `WouldBlock`.

[`writable`]: method@Self::writable

## tokio::poll_write_ready_mut (function)

Polls for write readiness.

If the file descriptor is not currently ready for writing, this method
will store a clone of the [`Waker`] from the provided [`Context`]. When the
file descriptor becomes ready for writing, [`Waker::wake`] will be called.

Note that on multiple calls to [`poll_write_ready`] or
[`poll_write_ready_mut`], only the `Waker` from the `Context` passed to the
most recent call is scheduled to receive a wakeup. (However,
[`poll_read_ready`] retains a second, independent waker).

This method is intended for cases where creating and pinning a future
via [`writable`] is not feasible. Where possible, using [`writable`] is
preferred, as this supports polling from multiple tasks at once.

This method takes `&mut self`, so it is possible to access the inner IO
resource mutably when handling the [`AsyncFdReadyMutGuard`].

[`poll_read_ready`]: method@Self::poll_read_ready
[`poll_write_ready`]: method@Self::poll_write_ready
[`poll_write_ready_mut`]: method@Self::poll_write_ready_mut
[`writable`]: method@Self::readable
[`Context`]: struct@std::task::Context
[`Waker`]: struct@std::task::Waker
[`Waker::wake`]: method@std::task::Waker::wake

## tokio::poll_write_vectored (function)

Like [`poll_write`], except that it writes from a slice of buffers.

Data is copied from each buffer in order, with the final buffer
read from possibly being only partially consumed. This method must
behave as a call to [`write`] with the buffers concatenated would.

The default implementation calls [`poll_write`] with either the first nonempty
buffer provided, or an empty one if none exists.

On success, returns `Poll::Ready(Ok(num_bytes_written))`.

If the object is not ready for writing, the method returns
`Poll::Pending` and arranges for the current task (via
`cx.waker()`) to receive a notification when the object becomes
writable or is closed.

### tokio::poll_write_vectored (function) › Note

This should be implemented as a single "atomic" write action. If any
data has been partially written, it is wrong to return an error or
pending.

[`poll_write`]: AsyncWrite::poll_write

## tokio::pre_exec (function)

Schedules a closure to be run just before the `exec` function is
invoked.

The closure is allowed to return an I/O error whose OS error code will
be communicated back to the parent and returned as an error from when
the spawn was requested.

Multiple closures can be registered and they will be called in order of
their registration. If a closure returns `Err` then no further closures
will be called and the spawn operation will immediately return with a
failure.

### tokio::pre_exec (function) › Safety

This closure will be run in the context of the child process after a
`fork`. This primarily means that any modifications made to memory on
behalf of this closure will **not** be visible to the parent process.
This is often a very constrained environment where normal operations
like `malloc` or acquiring a mutex are not guaranteed to work (due to
other threads perhaps still running when the `fork` was run).

This also means that all resources such as file descriptors and
memory-mapped regions got duplicated. It is your responsibility to make
sure that the closure does not violate library invariants by making
invalid use of these duplicates.

When this closure is run, aspects such as the stdio file descriptors and
working directory have successfully been changed, so output to these
locations may not appear where intended.

## tokio::precision_exact (function)

Sets the precision of this histogram directly.

The precision (meaning: the ratio `n/bucket_range(n)` for some given `n`) will be `2^-p`.

Precision controls the number consecutive buckets with identically sized ranges.
When `p` is 0, each bucket will be twice the size of the previous bucket (bucket groups are
only a single bucket wide).

To match the behavior of the legacy implementation ([`HistogramScale::Log`]), use `builder.precision_exact(0)`.

### tokio::precision_exact (function) › Panics
- `p` > 10

[`HistogramScale::Log`]: [crate::runtime::HistogramScale]

## tokio::process::Child (struct)

Representation of a child process spawned onto an event loop.

### tokio::process::Child (struct) › Caveats
Similar to the behavior to the standard library, and unlike the futures
paradigm of dropping-implies-cancellation, a spawned process will, by
default, continue to execute even after the `Child` handle has been dropped.

The `Command::kill_on_drop` method can be used to modify this behavior
and kill the child process if the `Child` wrapper is dropped before it
has exited.

## tokio::process::ChildStderr (struct)

The standard error stream for spawned children.

This type implements the `AsyncRead` trait to read data from the stderr
handle of a child process asynchronously.

## tokio::process::ChildStdin (struct)

The standard input stream for spawned children.

This type implements the `AsyncWrite` trait to pass data to the stdin
handle of a child process asynchronously.

## tokio::process::ChildStdout (struct)

The standard output stream for spawned children.

This type implements the `AsyncRead` trait to read data from the stdout
handle of a child process asynchronously.

## tokio::process::Command (struct)

This structure mimics the API of [`std::process::Command`] found in the standard library, but
replaces functions that create a process with an asynchronous variant. The main provided
asynchronous functions are [spawn](Command::spawn), [status](Command::status), and
[output](Command::output).

`Command` uses asynchronous versions of some `std` types (for example [`Child`]).

[`std::process::Command`]: std::process::Command
[`Child`]: struct@Child

## tokio::process_group (function)

Sets the process group ID (PGID) of the child process. Equivalent to a
`setpgid` call in the child process, but may be more efficient.

Process groups determine which processes receive signals.

### tokio::process_group (function) › Examples

Pressing Ctrl-C in a terminal will send `SIGINT` to all processes
in the current foreground process group. By spawning the `sleep`
subprocess in a new process group, it will not receive `SIGINT`
from the terminal.

The parent process could install a [signal handler] and manage the
process on its own terms.

A process group ID of 0 will use the process ID as the PGID.

```no_run
# async fn test() { // allow using await
use tokio::process::Command;

let output = Command::new("sleep")
    .arg("10")
    .process_group(0)
    .output()
    .await
    .unwrap();
# }
```

[signal handler]: crate::signal

## tokio::put_slice (function)

Appends data to the buffer, advancing the written position and possibly also the initialized position.

### tokio::put_slice (function) › Panics

Panics if `self.remaining()` is less than `buf.len()`.

## tokio::quickack (function)

Gets the value of the `TCP_QUICKACK` option on this socket.

For more information about this option, see [`TcpStream::set_quickack`].

### tokio::quickack (function) › Examples

```no_run
use tokio::net::TcpStream;

# async fn dox() -> Result<(), Box<dyn std::error::Error>> {
let stream = TcpStream::connect("127.0.0.1:8080").await?;

stream.quickack()?;
# Ok(())
# }
```

## tokio::quit (function)

Represents the `SIGQUIT` signal.

On Unix systems this signal is sent to issue a shutdown of the
process, after which the OS will dump the process core.
By default, the process is terminated by this signal.

## tokio::raw_arg (function)

Append literal text to the command line without any quoting or escaping.

This is useful for passing arguments to `cmd.exe /c`, which doesn't follow
`CommandLineToArgvW` escaping rules.

## tokio::raw_handle (function)

Extracts the raw handle of the process associated with this child while
it is still running. Returns `None` if the child has exited.

## tokio::read (function)

If the client supports reading data. This is enabled by default.

This corresponds to setting [`GENERIC_READ`] in the call to [`CreateFile`].

[`GENERIC_READ`]: https://docs.microsoft.com/en-us/windows/win32/secauthz/generic-access-rights
[`CreateFile`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew

## tokio::read (function)

Locks this `RwLock` with shared read access, causing the current task
to yield until the lock has been acquired.

The calling task will yield until there are no writers which hold the
lock. There may be other readers inside the lock when the task resumes.

Note that under the priority policy of [`RwLock`], read locks are not
granted until prior write locks, to prevent starvation. Therefore
deadlock may occur if a read lock is held by the current task, a write
lock attempt is made, and then a subsequent read lock attempt is made
by the current task.

Returns an RAII guard which will drop this read access of the `RwLock`
when dropped.

### tokio::read (function) › Cancel safety

This method uses a queue to fairly distribute locks in the order they
were requested. Cancelling a call to `read` makes you lose your place in
the queue.

### tokio::read (function) › Examples

```
use std::sync::Arc;
use tokio::sync::RwLock;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let lock = Arc::new(RwLock::new(1));
let c_lock = lock.clone();

let n = lock.read().await;
assert_eq!(*n, 1);

tokio::spawn(async move {
    // While main has an active read lock, we acquire one too.
    let r = c_lock.read().await;
    assert_eq!(*r, 1);
}).await.expect("The spawned task has panicked");

// Drop the guard after the spawned task finishes.
drop(n);
# }
```

## tokio::read (function)

Pulls some bytes from this source into the specified buffer,
returning how many bytes were read.

Equivalent to:

```ignore
async fn read(&mut self, buf: &mut [u8]) -> io::Result<usize>;
```

This method does not provide any guarantees about whether it
completes immediately or asynchronously.

### tokio::read (function) › Return

If the return value of this method is `Ok(n)`, then it must be
guaranteed that `0 <= n <= buf.len()`. A nonzero `n` value indicates
that the buffer `buf` has been filled in with `n` bytes of data from
this source. If `n` is `0`, then it can indicate one of two
scenarios:

1. This reader has reached its "end of file" and will likely no longer
   be able to produce bytes. Note that this does not mean that the
   reader will *always* no longer be able to produce bytes.
2. The buffer specified was 0 bytes in length.

No guarantees are provided about the contents of `buf` when this
function is called, implementations cannot rely on any property of the
contents of `buf` being true. It is recommended that *implementations*
only write data to `buf` instead of reading its contents.

Correspondingly, however, *callers* of this method may not assume
any guarantees about how the implementation uses `buf`. It is
possible that the code that's supposed to write to the buffer might
also read from it. It is your responsibility to make sure that `buf`
is initialized before calling `read`.

### tokio::read (function) › Errors

If this function encounters any form of I/O or other error, an error
variant will be returned. If an error is returned then it must be
guaranteed that no bytes were read.

### tokio::read (function) › Cancel safety

This method is cancel safe. If you use it as a branch in
[`tokio::select!`](crate::select) and another branch
completes first, then it is guaranteed that no data was read.

### tokio::read (function) › Examples

[`File`][crate::fs::File]s implement `Read`:

```no_run
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::fs::File;
use tokio::io::{self, AsyncReadExt};

#[tokio::main]
async fn main() -> io::Result<()> {
    let mut f = File::open("foo.txt").await?;
    let mut buffer = [0; 10];

    // read up to 10 bytes
    let n = f.read(&mut buffer[..]).await?;

    println!("The bytes: {:?}", &buffer[..n]);
    Ok(())
}
# }
```

## tokio::read (function)

Sets the option for read access.

This option, when true, will indicate that the file should be
`read`-able if opened.

This is an async version of [`std::fs::OpenOptions::read`][std]

[std]: std::fs::OpenOptions::read

### tokio::read (function) › Examples

```no_run
use tokio::fs::OpenOptions;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let file = OpenOptions::new()
        .read(true)
        .open("foo.txt")
        .await?;

    Ok(())
}
```

## tokio::read_buf (function)

Pulls some bytes from this source into the specified buffer,
advancing the buffer's internal cursor.

Equivalent to:

```ignore
async fn read_buf<B: BufMut>(&mut self, buf: &mut B) -> io::Result<usize>;
```

Usually, only a single `read` syscall is issued, even if there is
more space in the supplied buffer.

This method does not provide any guarantees about whether it
completes immediately or asynchronously.

### tokio::read_buf (function) › Return

A nonzero `n` value indicates that the buffer `buf` has been filled
in with `n` bytes of data from this source. If `n` is `0`, then it
can indicate one of two scenarios:

1. This reader has reached its "end of file" and will likely no longer
   be able to produce bytes. Note that this does not mean that the
   reader will *always* no longer be able to produce bytes.
2. The buffer specified had a remaining capacity of zero.

### tokio::read_buf (function) › Errors

If this function encounters any form of I/O or other error, an error
variant will be returned. If an error is returned then it must be
guaranteed that no bytes were read.

### tokio::read_buf (function) › Cancel safety

This method is cancel safe. If you use it as a branch in
[`tokio::select!`](crate::select) and another branch
completes first, then it is guaranteed that no data was read.

### tokio::read_buf (function) › Examples

[`File`] implements `Read` and [`BytesMut`] implements [`BufMut`]:

[`File`]: crate::fs::File
[`BytesMut`]: bytes::BytesMut
[`BufMut`]: bytes::BufMut

```no_run
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::fs::File;
use tokio::io::{self, AsyncReadExt};

use bytes::BytesMut;

#[tokio::main]
async fn main() -> io::Result<()> {
    let mut f = File::open("foo.txt").await?;
    let mut buffer = BytesMut::with_capacity(10);

    assert!(buffer.is_empty());
    assert!(buffer.capacity() >= 10);

    // note that the return value is not needed to access the data
    // that was read as `buffer`'s internal cursor is updated.
    //
    // this might read more than 10 bytes if the capacity of `buffer`
    // is larger than 10.
    f.read_buf(&mut buffer).await?;

    println!("The bytes: {:?}", &buffer[..]);
    Ok(())
}
# }
```

## tokio::read_exact (function)

Reads the exact number of bytes required to fill `buf`.

Equivalent to:

```ignore
async fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<usize>;
```

This function reads as many bytes as necessary to completely fill
the specified buffer `buf`.

### tokio::read_exact (function) › Errors

If the operation encounters an "end of file" before completely
filling the buffer, it returns an error of the kind
[`ErrorKind::UnexpectedEof`]. The contents of `buf` are unspecified
in this case.

If any other read error is encountered then the operation
immediately returns. The contents of `buf` are unspecified in this
case.

If this operation returns an error, it is unspecified how many bytes
it has read, but it will never read more than would be necessary to
completely fill the buffer.

### tokio::read_exact (function) › Cancel safety

This method is not cancel safe. If the method is used as a
branch in [`tokio::select!`](crate::select) and another
branch completes first, then some data may already have been
read into `buf`.

### tokio::read_exact (function) › Examples

[`File`][crate::fs::File]s implement `Read`:

```no_run
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::fs::File;
use tokio::io::{self, AsyncReadExt};

#[tokio::main]
async fn main() -> io::Result<()> {
    let mut f = File::open("foo.txt").await?;
    let len = 10;
    let mut buffer = vec![0; len];

    // read exactly 10 bytes
    f.read_exact(&mut buffer).await?;
    Ok(())
}
# }
```

[`ErrorKind::UnexpectedEof`]: std::io::ErrorKind::UnexpectedEof

## tokio::read_f32 (function)

Reads an 32-bit floating point type in big-endian order from the
underlying reader.

Equivalent to:

```ignore
async fn read_f32(&mut self) -> io::Result<f32>;
```

It is recommended to use a buffered reader to avoid excessive
syscalls.

### tokio::read_f32 (function) › Errors

This method returns the same errors as [`AsyncReadExt::read_exact`].

[`AsyncReadExt::read_exact`]: AsyncReadExt::read_exact

### tokio::read_f32 (function) › Cancel safety

This method is not cancel safe. If the method is used as a
branch in [`tokio::select!`](crate::select) and another
branch completes first, then some data may be lost.

### tokio::read_f32 (function) › Examples

Read 32-bit floating point type from a `AsyncRead`:

```rust
use tokio::io::{self, AsyncReadExt};

use std::io::Cursor;

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut reader = Cursor::new(vec![0xff, 0x7f, 0xff, 0xff]);

assert_eq!(f32::MIN, reader.read_f32().await?);
Ok(())
# }
```

## tokio::read_f32_le (function)

Reads an 32-bit floating point type in little-endian order from the
underlying reader.

Equivalent to:

```ignore
async fn read_f32_le(&mut self) -> io::Result<f32>;
```

It is recommended to use a buffered reader to avoid excessive
syscalls.

### tokio::read_f32_le (function) › Errors

This method returns the same errors as [`AsyncReadExt::read_exact`].

[`AsyncReadExt::read_exact`]: AsyncReadExt::read_exact

### tokio::read_f32_le (function) › Cancel safety

This method is not cancel safe. If the method is used as a
branch in [`tokio::select!`](crate::select) and another
branch completes first, then some data may be lost.

### tokio::read_f32_le (function) › Examples

Read 32-bit floating point type from a `AsyncRead`:

```rust
use tokio::io::{self, AsyncReadExt};

use std::io::Cursor;

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut reader = Cursor::new(vec![0xff, 0xff, 0x7f, 0xff]);

assert_eq!(f32::MIN, reader.read_f32_le().await?);
Ok(())
# }
```

## tokio::read_f64 (function)

Reads an 64-bit floating point type in big-endian order from the
underlying reader.

Equivalent to:

```ignore
async fn read_f64(&mut self) -> io::Result<f64>;
```

It is recommended to use a buffered reader to avoid excessive
syscalls.

### tokio::read_f64 (function) › Errors

This method returns the same errors as [`AsyncReadExt::read_exact`].

[`AsyncReadExt::read_exact`]: AsyncReadExt::read_exact

### tokio::read_f64 (function) › Cancel safety

This method is not cancel safe. If the method is used as a
branch in [`tokio::select!`](crate::select) and another
branch completes first, then some data may be lost.

### tokio::read_f64 (function) › Examples

Read 64-bit floating point type from a `AsyncRead`:

```rust
use tokio::io::{self, AsyncReadExt};

use std::io::Cursor;

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut reader = Cursor::new(vec![
    0xff, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
]);

assert_eq!(f64::MIN, reader.read_f64().await?);
Ok(())
# }
```

## tokio::read_f64_le (function)

Reads an 64-bit floating point type in little-endian order from the
underlying reader.

Equivalent to:

```ignore
async fn read_f64_le(&mut self) -> io::Result<f64>;
```

It is recommended to use a buffered reader to avoid excessive
syscalls.

### tokio::read_f64_le (function) › Errors

This method returns the same errors as [`AsyncReadExt::read_exact`].

[`AsyncReadExt::read_exact`]: AsyncReadExt::read_exact

### tokio::read_f64_le (function) › Cancel safety

This method is not cancel safe. If the method is used as a
branch in [`tokio::select!`](crate::select) and another
branch completes first, then some data may be lost.

### tokio::read_f64_le (function) › Examples

Read 64-bit floating point type from a `AsyncRead`:

```rust
use tokio::io::{self, AsyncReadExt};

use std::io::Cursor;

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut reader = Cursor::new(vec![
    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff
]);

assert_eq!(f64::MIN, reader.read_f64_le().await?);
Ok(())
# }
```

## tokio::read_i128 (function)

Reads an signed 128-bit integer in big-endian order from the
underlying reader.

Equivalent to:

```ignore
async fn read_i128(&mut self) -> io::Result<i128>;
```

It is recommended to use a buffered reader to avoid excessive
syscalls.

### tokio::read_i128 (function) › Errors

This method returns the same errors as [`AsyncReadExt::read_exact`].

[`AsyncReadExt::read_exact`]: AsyncReadExt::read_exact

### tokio::read_i128 (function) › Cancel safety

This method is not cancel safe. If the method is used as a
branch in [`tokio::select!`](crate::select) and another
branch completes first, then some data may be lost.

### tokio::read_i128 (function) › Examples

Read signed 128-bit big-endian integers from a `AsyncRead`:

```rust
use tokio::io::{self, AsyncReadExt};

use std::io::Cursor;

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut reader = Cursor::new(vec![
    0x80, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0
]);

assert_eq!(i128::MIN, reader.read_i128().await?);
Ok(())
# }
```

## tokio::read_i128_le (function)

Reads an signed 128-bit integer in little-endian order from the
underlying reader.

Equivalent to:

```ignore
async fn read_i128_le(&mut self) -> io::Result<i128>;
```

It is recommended to use a buffered reader to avoid excessive
syscalls.

### tokio::read_i128_le (function) › Errors

This method returns the same errors as [`AsyncReadExt::read_exact`].

[`AsyncReadExt::read_exact`]: AsyncReadExt::read_exact

### tokio::read_i128_le (function) › Cancel safety

This method is not cancel safe. If the method is used as a
branch in [`tokio::select!`](crate::select) and another
branch completes first, then some data may be lost.

### tokio::read_i128_le (function) › Examples

Read signed 128-bit little-endian integers from a `AsyncRead`:

```rust
use tokio::io::{self, AsyncReadExt};

use std::io::Cursor;

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut reader = Cursor::new(vec![
    0x80, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0
]);

assert_eq!(128, reader.read_i128_le().await?);
Ok(())
# }
```

## tokio::read_i16 (function)

Reads a signed 16-bit integer in big-endian order from the
underlying reader.

Equivalent to:

```ignore
async fn read_i16(&mut self) -> io::Result<i16>;
```

It is recommended to use a buffered reader to avoid excessive
syscalls.

### tokio::read_i16 (function) › Errors

This method returns the same errors as [`AsyncReadExt::read_exact`].

[`AsyncReadExt::read_exact`]: AsyncReadExt::read_exact

### tokio::read_i16 (function) › Cancel safety

This method is not cancel safe. If the method is used as a
branch in [`tokio::select!`](crate::select) and another
branch completes first, then some data may be lost.

### tokio::read_i16 (function) › Examples

Read signed 16 bit big-endian integers from a `AsyncRead`:

```rust
use tokio::io::{self, AsyncReadExt};

use std::io::Cursor;

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut reader = Cursor::new(vec![0x00, 0xc1, 0xff, 0x7c]);

assert_eq!(193, reader.read_i16().await?);
assert_eq!(-132, reader.read_i16().await?);
Ok(())
# }
```

## tokio::read_i16_le (function)

Reads a signed 16-bit integer in little-endian order from the
underlying reader.

Equivalent to:

```ignore
async fn read_i16_le(&mut self) -> io::Result<i16>;
```

It is recommended to use a buffered reader to avoid excessive
syscalls.

### tokio::read_i16_le (function) › Errors

This method returns the same errors as [`AsyncReadExt::read_exact`].

[`AsyncReadExt::read_exact`]: AsyncReadExt::read_exact

### tokio::read_i16_le (function) › Cancel safety

This method is not cancel safe. If the method is used as a
branch in [`tokio::select!`](crate::select) and another
branch completes first, then some data may be lost.

### tokio::read_i16_le (function) › Examples

Read signed 16 bit little-endian integers from a `AsyncRead`:

```rust
use tokio::io::{self, AsyncReadExt};

use std::io::Cursor;

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut reader = Cursor::new(vec![0x00, 0xc1, 0xff, 0x7c]);

assert_eq!(-16128, reader.read_i16_le().await?);
assert_eq!(31999, reader.read_i16_le().await?);
Ok(())
# }
```

## tokio::read_i32 (function)

Reads a signed 32-bit integer in big-endian order from the
underlying reader.


Equivalent to:

```ignore
async fn read_i32(&mut self) -> io::Result<i32>;
```

It is recommended to use a buffered reader to avoid excessive
syscalls.

### tokio::read_i32 (function) › Errors

This method returns the same errors as [`AsyncReadExt::read_exact`].

[`AsyncReadExt::read_exact`]: AsyncReadExt::read_exact

### tokio::read_i32 (function) › Cancel safety

This method is not cancel safe. If the method is used as a
branch in [`tokio::select!`](crate::select) and another
branch completes first, then some data may be lost.

### tokio::read_i32 (function) › Examples

Read signed 32-bit big-endian integers from a `AsyncRead`:

```rust
use tokio::io::{self, AsyncReadExt};

use std::io::Cursor;

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut reader = Cursor::new(vec![0xff, 0xff, 0x7a, 0x33]);

assert_eq!(-34253, reader.read_i32().await?);
Ok(())
# }
```

## tokio::read_i32_le (function)

Reads a signed 32-bit integer in little-endian order from the
underlying reader.


Equivalent to:

```ignore
async fn read_i32_le(&mut self) -> io::Result<i32>;
```

It is recommended to use a buffered reader to avoid excessive
syscalls.

### tokio::read_i32_le (function) › Errors

This method returns the same errors as [`AsyncReadExt::read_exact`].

[`AsyncReadExt::read_exact`]: AsyncReadExt::read_exact

### tokio::read_i32_le (function) › Cancel safety

This method is not cancel safe. If the method is used as a
branch in [`tokio::select!`](crate::select) and another
branch completes first, then some data may be lost.

### tokio::read_i32_le (function) › Examples

Read signed 32-bit little-endian integers from a `AsyncRead`:

```rust
use tokio::io::{self, AsyncReadExt};

use std::io::Cursor;

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut reader = Cursor::new(vec![0xff, 0xff, 0x7a, 0x33]);

assert_eq!(863698943, reader.read_i32_le().await?);
Ok(())
# }
```

## tokio::read_i64 (function)

Reads an signed 64-bit integer in big-endian order from the
underlying reader.

Equivalent to:

```ignore
async fn read_i64(&mut self) -> io::Result<i64>;
```

It is recommended to use a buffered reader to avoid excessive
syscalls.

### tokio::read_i64 (function) › Errors

This method returns the same errors as [`AsyncReadExt::read_exact`].

[`AsyncReadExt::read_exact`]: AsyncReadExt::read_exact

### tokio::read_i64 (function) › Cancel safety

This method is not cancel safe. If the method is used as a
branch in [`tokio::select!`](crate::select) and another
branch completes first, then some data may be lost.

### tokio::read_i64 (function) › Examples

Read signed 64-bit big-endian integers from a `AsyncRead`:

```rust
use tokio::io::{self, AsyncReadExt};

use std::io::Cursor;

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut reader = Cursor::new(vec![0x80, 0, 0, 0, 0, 0, 0, 0]);

assert_eq!(i64::MIN, reader.read_i64().await?);
Ok(())
# }
```

## tokio::read_i64_le (function)

Reads an signed 64-bit integer in little-endian order from the
underlying reader.

Equivalent to:

```ignore
async fn read_i64_le(&mut self) -> io::Result<i64>;
```

It is recommended to use a buffered reader to avoid excessive
syscalls.

### tokio::read_i64_le (function) › Errors

This method returns the same errors as [`AsyncReadExt::read_exact`].

[`AsyncReadExt::read_exact`]: AsyncReadExt::read_exact

### tokio::read_i64_le (function) › Cancel safety

This method is not cancel safe. If the method is used as a
branch in [`tokio::select!`](crate::select) and another
branch completes first, then some data may be lost.

### tokio::read_i64_le (function) › Examples

Read signed 64-bit little-endian integers from a `AsyncRead`:

```rust
use tokio::io::{self, AsyncReadExt};

use std::io::Cursor;

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut reader = Cursor::new(vec![0x80, 0, 0, 0, 0, 0, 0, 0]);

assert_eq!(128, reader.read_i64_le().await?);
Ok(())
# }
```

## tokio::read_i8 (function)

Reads a signed 8 bit integer from the underlying reader.

Equivalent to:

```ignore
async fn read_i8(&mut self) -> io::Result<i8>;
```

It is recommended to use a buffered reader to avoid excessive
syscalls.

### tokio::read_i8 (function) › Errors

This method returns the same errors as [`AsyncReadExt::read_exact`].

[`AsyncReadExt::read_exact`]: AsyncReadExt::read_exact

### tokio::read_i8 (function) › Cancel safety

This method is cancel safe. If this method is used as a branch in
[`tokio::select!`](crate::select) and another branch
completes first, it is guaranteed that no data were read.

### tokio::read_i8 (function) › Examples

Read unsigned 8 bit integers from an `AsyncRead`:

```rust
use tokio::io::{self, AsyncReadExt};

use std::io::Cursor;

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut reader = Cursor::new(vec![0x02, 0xfb]);

assert_eq!(2, reader.read_i8().await?);
assert_eq!(-5, reader.read_i8().await?);

Ok(())
# }
```

## tokio::read_line (function)

Reads all bytes until a newline (the 0xA byte) is reached, and append
them to the provided buffer.

Equivalent to:

```ignore
async fn read_line(&mut self, buf: &mut String) -> io::Result<usize>;
```

This function will read bytes from the underlying stream until the
newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes
up to, and including, the delimiter (if found) will be appended to
`buf`.

If successful, this function will return the total number of bytes read.

If this function returns `Ok(0)`, the stream has reached EOF.

### tokio::read_line (function) › Errors

This function has the same error semantics as [`read_until`] and will
also return an error if the read bytes are not valid UTF-8. If an I/O
error is encountered then `buf` may contain some bytes already read in
the event that all data read so far was valid UTF-8.

[`read_until`]: AsyncBufReadExt::read_until

### tokio::read_line (function) › Cancel safety

This method is not cancel safe. If the method is used as a
branch in [`tokio::select!`](crate::select) and another
branch completes first, then some data may have been partially
read, and this data is lost. There are no guarantees regarding the
contents of `buf` when the call is cancelled. The current
implementation replaces `buf` with the empty string, but this may
change in the future.

This function does not behave like [`read_until`] because of the
requirement that a string contains only valid utf-8. If you need a
cancellation safe `read_line`, there are three options:

 * Call [`read_until`] with a newline character and manually perform the utf-8 check.
 * The stream returned by [`lines`] has a cancellation safe
   [`next_line`] method.
 * Use [`tokio_util::codec::LinesCodec`][LinesCodec].

[LinesCodec]: https://docs.rs/tokio-util/latest/tokio_util/codec/struct.LinesCodec.html
[`read_until`]: Self::read_until
[`lines`]: Self::lines
[`next_line`]: crate::io::Lines::next_line

### tokio::read_line (function) › Examples

[`std::io::Cursor`][`Cursor`] is a type that implements
`AsyncBufRead`. In this example, we use [`Cursor`] to read all the
lines in a byte slice:

[`Cursor`]: std::io::Cursor

```
use tokio::io::AsyncBufReadExt;

use std::io::Cursor;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let mut cursor = Cursor::new(b"foo\nbar");
let mut buf = String::new();

// cursor is at 'f'
let num_bytes = cursor.read_line(&mut buf)
    .await
    .expect("reading from cursor won't fail");

assert_eq!(num_bytes, 4);
assert_eq!(buf, "foo\n");
buf.clear();

// cursor is at 'b'
let num_bytes = cursor.read_line(&mut buf)
    .await
    .expect("reading from cursor won't fail");

assert_eq!(num_bytes, 3);
assert_eq!(buf, "bar");
buf.clear();

// cursor is at EOF
let num_bytes = cursor.read_line(&mut buf)
    .await
    .expect("reading from cursor won't fail");

assert_eq!(num_bytes, 0);
assert_eq!(buf, "");
# }
```

## tokio::read_owned (function)

 Locks this `RwLock` with shared read access, causing the current task
 to yield until the lock has been acquired.

 The calling task will yield until there are no writers which hold the
 lock. There may be other readers inside the lock when the task resumes.

 This method is identical to [`RwLock::read`], except that the returned
 guard references the `RwLock` with an [`Arc`] rather than by borrowing
 it. Therefore, the `RwLock` must be wrapped in an `Arc` to call this
 method, and the guard will live for the `'static` lifetime, as it keeps
 the `RwLock` alive by holding an `Arc`.

 Note that under the priority policy of [`RwLock`], read locks are not
 granted until prior write locks, to prevent starvation. Therefore
 deadlock may occur if a read lock is held by the current task, a write
 lock attempt is made, and then a subsequent read lock attempt is made
 by the current task.

 Returns an RAII guard which will drop this read access of the `RwLock`
 when dropped.

### tokio::read_owned (function) › Cancel safety

 This method uses a queue to fairly distribute locks in the order they
 were requested. Cancelling a call to `read_owned` makes you lose your
 place in the queue.

### tokio::read_owned (function) › Examples

 ```
 use std::sync::Arc;
 use tokio::sync::RwLock;

 # #[tokio::main(flavor = "current_thread")]
 # async fn main() {
 let lock = Arc::new(RwLock::new(1));
 let c_lock = lock.clone();

 let n = lock.read_owned().await;
 assert_eq!(*n, 1);

 tokio::spawn(async move {
     // While main has an active read lock, we acquire one too.
     let r = c_lock.read_owned().await;
     assert_eq!(*r, 1);
 }).await.expect("The spawned task has panicked");

 // Drop the guard after the spawned task finishes.
 drop(n);
}
 ```

## tokio::read_to_end (function)

Reads all bytes until EOF in this source, placing them into `buf`.

Equivalent to:

```ignore
async fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize>;
```

All bytes read from this source will be appended to the specified
buffer `buf`. This function will continuously call [`read()`] to
append more data to `buf` until [`read()`] returns `Ok(0)`.

If successful, the total number of bytes read is returned.

[`read()`]: AsyncReadExt::read

### tokio::read_to_end (function) › Errors

If a read error is encountered then the `read_to_end` operation
immediately completes. Any bytes which have already been read will
be appended to `buf`.

### tokio::read_to_end (function) › Examples

[`File`][crate::fs::File]s implement `Read`:

```no_run
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::io::{self, AsyncReadExt};
use tokio::fs::File;

#[tokio::main]
async fn main() -> io::Result<()> {
    let mut f = File::open("foo.txt").await?;
    let mut buffer = Vec::new();

    // read the whole file
    f.read_to_end(&mut buffer).await?;
    Ok(())
}
# }
```

(See also the [`tokio::fs::read`] convenience function for reading from a
file.)

[`tokio::fs::read`]: fn@crate::fs::read

## tokio::read_to_string (function)

Reads all bytes until EOF in this source, appending them to `buf`.

Equivalent to:

```ignore
async fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize>;
```

If successful, the number of bytes which were read and appended to
`buf` is returned.

### tokio::read_to_string (function) › Errors

If the data in this stream is *not* valid UTF-8 then an error is
returned and `buf` is unchanged.

See [`read_to_end`][AsyncReadExt::read_to_end] for other error semantics.

### tokio::read_to_string (function) › Examples

[`File`][crate::fs::File]s implement `Read`:

```no_run
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::io::{self, AsyncReadExt};
use tokio::fs::File;

#[tokio::main]
async fn main() -> io::Result<()> {
    let mut f = File::open("foo.txt").await?;
    let mut buffer = String::new();

    f.read_to_string(&mut buffer).await?;
    Ok(())
}
# }
```

(See also the [`crate::fs::read_to_string`] convenience function for
reading from a file.)

[`crate::fs::read_to_string`]: fn@crate::fs::read_to_string

## tokio::read_u128 (function)

Reads an unsigned 128-bit integer in big-endian order from the
underlying reader.

Equivalent to:

```ignore
async fn read_u128(&mut self) -> io::Result<u128>;
```

It is recommended to use a buffered reader to avoid excessive
syscalls.

### tokio::read_u128 (function) › Errors

This method returns the same errors as [`AsyncReadExt::read_exact`].

[`AsyncReadExt::read_exact`]: AsyncReadExt::read_exact

### tokio::read_u128 (function) › Cancel safety

This method is not cancel safe. If the method is used as a
branch in [`tokio::select!`](crate::select) and another
branch completes first, then some data may be lost.

### tokio::read_u128 (function) › Examples

Read unsigned 128-bit big-endian integers from a `AsyncRead`:

```rust
use tokio::io::{self, AsyncReadExt};

use std::io::Cursor;

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut reader = Cursor::new(vec![
        0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83,
    0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83
]);

assert_eq!(16947640962301618749969007319746179, reader.read_u128().await?);
Ok(())
# }
```

## tokio::read_u128_le (function)

Reads an unsigned 128-bit integer in little-endian order from the
underlying reader.

Equivalent to:

```ignore
async fn read_u128_le(&mut self) -> io::Result<u128>;
```

It is recommended to use a buffered reader to avoid excessive
syscalls.

### tokio::read_u128_le (function) › Errors

This method returns the same errors as [`AsyncReadExt::read_exact`].

[`AsyncReadExt::read_exact`]: AsyncReadExt::read_exact

### tokio::read_u128_le (function) › Cancel safety

This method is not cancel safe. If the method is used as a
branch in [`tokio::select!`](crate::select) and another
branch completes first, then some data may be lost.

### tokio::read_u128_le (function) › Examples

Read unsigned 128-bit little-endian integers from a `AsyncRead`:

```rust
use tokio::io::{self, AsyncReadExt};

use std::io::Cursor;

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut reader = Cursor::new(vec![
    0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83,
    0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83
]);

assert_eq!(174826588484952389081207917399662330624, reader.read_u128_le().await?);
Ok(())
# }
```

## tokio::read_u16 (function)

Reads an unsigned 16-bit integer in big-endian order from the
underlying reader.

Equivalent to:

```ignore
async fn read_u16(&mut self) -> io::Result<u16>;
```

It is recommended to use a buffered reader to avoid excessive
syscalls.

### tokio::read_u16 (function) › Errors

This method returns the same errors as [`AsyncReadExt::read_exact`].

[`AsyncReadExt::read_exact`]: AsyncReadExt::read_exact

### tokio::read_u16 (function) › Cancel safety

This method is not cancel safe. If the method is used as a
branch in [`tokio::select!`](crate::select) and another
branch completes first, then some data may be lost.

### tokio::read_u16 (function) › Examples

Read unsigned 16 bit big-endian integers from a `AsyncRead`:

```rust
use tokio::io::{self, AsyncReadExt};

use std::io::Cursor;

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut reader = Cursor::new(vec![2, 5, 3, 0]);

assert_eq!(517, reader.read_u16().await?);
assert_eq!(768, reader.read_u16().await?);
Ok(())
# }
```

## tokio::read_u16_le (function)

Reads an unsigned 16-bit integer in little-endian order from the
underlying reader.

Equivalent to:

```ignore
async fn read_u16_le(&mut self) -> io::Result<u16>;
```

It is recommended to use a buffered reader to avoid excessive
syscalls.

### tokio::read_u16_le (function) › Errors

This method returns the same errors as [`AsyncReadExt::read_exact`].

[`AsyncReadExt::read_exact`]: AsyncReadExt::read_exact

### tokio::read_u16_le (function) › Cancel safety

This method is not cancel safe. If the method is used as a
branch in [`tokio::select!`](crate::select) and another
branch completes first, then some data may be lost.

### tokio::read_u16_le (function) › Examples

Read unsigned 16 bit little-endian integers from a `AsyncRead`:

```rust
use tokio::io::{self, AsyncReadExt};

use std::io::Cursor;

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut reader = Cursor::new(vec![2, 5, 3, 0]);

assert_eq!(1282, reader.read_u16_le().await?);
assert_eq!(3, reader.read_u16_le().await?);
Ok(())
# }
```

## tokio::read_u32 (function)

Reads an unsigned 32-bit integer in big-endian order from the
underlying reader.

Equivalent to:

```ignore
async fn read_u32(&mut self) -> io::Result<u32>;
```

It is recommended to use a buffered reader to avoid excessive
syscalls.

### tokio::read_u32 (function) › Errors

This method returns the same errors as [`AsyncReadExt::read_exact`].

[`AsyncReadExt::read_exact`]: AsyncReadExt::read_exact

### tokio::read_u32 (function) › Cancel safety

This method is not cancel safe. If the method is used as a
branch in [`tokio::select!`](crate::select) and another
branch completes first, then some data may be lost.

### tokio::read_u32 (function) › Examples

Read unsigned 32-bit big-endian integers from a `AsyncRead`:

```rust
use tokio::io::{self, AsyncReadExt};

use std::io::Cursor;

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut reader = Cursor::new(vec![0x00, 0x00, 0x01, 0x0b]);

assert_eq!(267, reader.read_u32().await?);
Ok(())
# }
```

## tokio::read_u32_le (function)

Reads an unsigned 32-bit integer in little-endian order from the
underlying reader.

Equivalent to:

```ignore
async fn read_u32_le(&mut self) -> io::Result<u32>;
```

It is recommended to use a buffered reader to avoid excessive
syscalls.

### tokio::read_u32_le (function) › Errors

This method returns the same errors as [`AsyncReadExt::read_exact`].

[`AsyncReadExt::read_exact`]: AsyncReadExt::read_exact

### tokio::read_u32_le (function) › Cancel safety

This method is not cancel safe. If the method is used as a
branch in [`tokio::select!`](crate::select) and another
branch completes first, then some data may be lost.

### tokio::read_u32_le (function) › Examples

Read unsigned 32-bit little-endian integers from a `AsyncRead`:

```rust
use tokio::io::{self, AsyncReadExt};

use std::io::Cursor;

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut reader = Cursor::new(vec![0x00, 0x00, 0x01, 0x0b]);

assert_eq!(184614912, reader.read_u32_le().await?);
Ok(())
# }
```

## tokio::read_u64 (function)

Reads an unsigned 64-bit integer in big-endian order from the
underlying reader.

Equivalent to:

```ignore
async fn read_u64(&mut self) -> io::Result<u64>;
```

It is recommended to use a buffered reader to avoid excessive
syscalls.

### tokio::read_u64 (function) › Errors

This method returns the same errors as [`AsyncReadExt::read_exact`].

[`AsyncReadExt::read_exact`]: AsyncReadExt::read_exact

### tokio::read_u64 (function) › Cancel safety

This method is not cancel safe. If the method is used as a
branch in [`tokio::select!`](crate::select) and another
branch completes first, then some data may be lost.

### tokio::read_u64 (function) › Examples

Read unsigned 64-bit big-endian integers from a `AsyncRead`:

```rust
use tokio::io::{self, AsyncReadExt};

use std::io::Cursor;

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut reader = Cursor::new(vec![
    0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83
]);

assert_eq!(918733457491587, reader.read_u64().await?);
Ok(())
# }
```

## tokio::read_u64_le (function)

Reads an unsigned 64-bit integer in little-endian order from the
underlying reader.

Equivalent to:

```ignore
async fn read_u64_le(&mut self) -> io::Result<u64>;
```

It is recommended to use a buffered reader to avoid excessive
syscalls.

### tokio::read_u64_le (function) › Errors

This method returns the same errors as [`AsyncReadExt::read_exact`].

[`AsyncReadExt::read_exact`]: AsyncReadExt::read_exact

### tokio::read_u64_le (function) › Cancel safety

This method is not cancel safe. If the method is used as a
branch in [`tokio::select!`](crate::select) and another
branch completes first, then some data may be lost.

### tokio::read_u64_le (function) › Examples

Read unsigned 64-bit little-endian integers from a `AsyncRead`:

```rust
use tokio::io::{self, AsyncReadExt};

use std::io::Cursor;

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut reader = Cursor::new(vec![
    0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83
]);

assert_eq!(9477368352180732672, reader.read_u64_le().await?);
Ok(())
# }
```

## tokio::read_u8 (function)

Reads an unsigned 8 bit integer from the underlying reader.

Equivalent to:

```ignore
async fn read_u8(&mut self) -> io::Result<u8>;
```

It is recommended to use a buffered reader to avoid excessive
syscalls.

### tokio::read_u8 (function) › Errors

This method returns the same errors as [`AsyncReadExt::read_exact`].

[`AsyncReadExt::read_exact`]: AsyncReadExt::read_exact

### tokio::read_u8 (function) › Cancel safety

This method is cancel safe. If this method is used as a branch in
[`tokio::select!`](crate::select) and another branch
completes first, it is guaranteed that no data were read.

### tokio::read_u8 (function) › Examples

Read unsigned 8 bit integers from an `AsyncRead`:

```rust
use tokio::io::{self, AsyncReadExt};

use std::io::Cursor;

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut reader = Cursor::new(vec![2, 5]);

assert_eq!(2, reader.read_u8().await?);
assert_eq!(5, reader.read_u8().await?);

Ok(())
# }
```

## tokio::read_until (function)

Reads all bytes into `buf` until the delimiter `byte` or EOF is reached.

Equivalent to:

```ignore
async fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> io::Result<usize>;
```

This function will read bytes from the underlying stream until the
delimiter or EOF is found. Once found, all bytes up to, and including,
the delimiter (if found) will be appended to `buf`.

If successful, this function will return the total number of bytes read.

If this function returns `Ok(0)`, the stream has reached EOF.

### tokio::read_until (function) › Errors

This function will ignore all instances of [`ErrorKind::Interrupted`] and
will otherwise return any errors returned by [`fill_buf`].

If an I/O error is encountered then all bytes read so far will be
present in `buf` and its length will have been adjusted appropriately.

[`fill_buf`]: AsyncBufRead::poll_fill_buf
[`ErrorKind::Interrupted`]: std::io::ErrorKind::Interrupted

### tokio::read_until (function) › Cancel safety

If used as a branch in
[`tokio::select!`](crate::select) and another branch
completes first, then some data may have been partially read. Any
partially read bytes are appended to `buf`, and the method can be
called again to continue reading until `byte`.

This method returns the total number of bytes read. If you cancel
the call to `read_until` and then call it again to continue reading,
the counter is reset.

### tokio::read_until (function) › Examples

[`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
this example, we use [`Cursor`] to read all the bytes in a byte slice
in hyphen delimited segments:

[`Cursor`]: std::io::Cursor

```
use tokio::io::AsyncBufReadExt;

use std::io::Cursor;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let mut cursor = Cursor::new(b"lorem-ipsum");
let mut buf = vec![];

// cursor is at 'l'
let num_bytes = cursor.read_until(b'-', &mut buf)
    .await
    .expect("reading from cursor won't fail");

assert_eq!(num_bytes, 6);
assert_eq!(buf, b"lorem-");
buf.clear();

// cursor is at 'i'
let num_bytes = cursor.read_until(b'-', &mut buf)
    .await
    .expect("reading from cursor won't fail");

assert_eq!(num_bytes, 5);
assert_eq!(buf, b"ipsum");
buf.clear();

// cursor is at EOF
let num_bytes = cursor.read_until(b'-', &mut buf)
    .await
    .expect("reading from cursor won't fail");
assert_eq!(num_bytes, 0);
assert_eq!(buf, b"");
# }
```

## tokio::read_write (function)

Sets the option for read-write access.

This option, when true, will indicate that a FIFO file will be opened
in read-write access mode. This operation is not defined by the POSIX
standard and is only guaranteed to work on Linux.

### tokio::read_write (function) › Examples

Opening a [`Sender`] even if there are no open reading ends:

```ignore
use tokio::net::unix::pipe;

let tx = pipe::OpenOptions::new()
    .read_write(true)
    .open_sender("path/to/a/fifo");
```

Opening a resilient [`Receiver`] i.e. a reading pipe end which will not
fail with [`UnexpectedEof`] during reading if all writing ends of the
pipe close the FIFO file.

[`UnexpectedEof`]: std::io::ErrorKind::UnexpectedEof

```ignore
use tokio::net::unix::pipe;

let tx = pipe::OpenOptions::new()
    .read_write(true)
    .open_receiver("path/to/a/fifo");
```

## tokio::readable (function)

Waits for the file descriptor to become readable, returning a
[`AsyncFdReadyGuard`] that must be dropped to resume read-readiness
polling.

This method takes `&self`, so it is possible to call this method
concurrently with other methods on this struct. This method only
provides shared access to the inner IO resource when handling the
[`AsyncFdReadyGuard`].

### tokio::readable (function) › Cancel safety

This method is cancel safe. Once a readiness event occurs, the method
will continue to return immediately until the readiness event is
consumed by an attempt to read or write that fails with `WouldBlock` or
`Poll::Pending`.

## tokio::readable (function)

Waits for the pipe to become readable.

This function is equivalent to `ready(Interest::READABLE)` and is usually
paired with [`try_read()`].

[`try_read()`]: Self::try_read()

### tokio::readable (function) › Examples

```no_run
use tokio::net::unix::pipe;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    // Open a reading end of a fifo
    let rx = pipe::OpenOptions::new().open_receiver("path/to/a/fifo")?;

    let mut msg = vec![0; 1024];

    loop {
        // Wait for the pipe to be readable
        rx.readable().await?;

        // Try to read data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match rx.try_read(&mut msg) {
            Ok(n) => {
                msg.truncate(n);
                break;
            }
            Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    println!("GOT = {:?}", msg);
    Ok(())
}
```

## tokio::readable (function)

Waits for the pipe to become readable.

This function is equivalent to `ready(Interest::READABLE)` and is usually
paired with `try_read()`.

### tokio::readable (function) › Examples

```no_run
use tokio::net::windows::named_pipe;
use std::error::Error;
use std::io;

const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-client-readable";

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let client = named_pipe::ClientOptions::new().open(PIPE_NAME)?;

    let mut msg = vec![0; 1024];

    loop {
        // Wait for the pipe to be readable
        client.readable().await?;

        // Try to read data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match client.try_read(&mut msg) {
            Ok(n) => {
                msg.truncate(n);
                break;
            }
            Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    println!("GOT = {:?}", msg);
    Ok(())
}
```

## tokio::readable (function)

Waits for the pipe to become readable.

This function is equivalent to `ready(Interest::READABLE)` and is usually
paired with `try_read()`.

### tokio::readable (function) › Examples

```no_run
use tokio::net::windows::named_pipe;
use std::error::Error;
use std::io;

const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-server-readable";

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let server = named_pipe::ServerOptions::new()
        .create(PIPE_NAME)?;

    let mut msg = vec![0; 1024];

    loop {
        // Wait for the pipe to be readable
        server.readable().await?;

        // Try to read data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match server.try_read(&mut msg) {
            Ok(n) => {
                msg.truncate(n);
                break;
            }
            Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    println!("GOT = {:?}", msg);
    Ok(())
}
```

## tokio::readable (function)

Waits for the socket to become readable.

This function is equivalent to `ready(Interest::READABLE)` and is usually
paired with `try_read()`.

### tokio::readable (function) › Cancel safety

This method is cancel safe. Once a readiness event occurs, the method
will continue to return immediately until the readiness event is
consumed by an attempt to read that fails with `WouldBlock` or
`Poll::Pending`.

## tokio::readable (function)

Waits for the socket to become readable.

This function is equivalent to `ready(Interest::READABLE)` and is usually
paired with `try_read()`.

### tokio::readable (function) › Cancel safety

This method is cancel safe. Once a readiness event occurs, the method
will continue to return immediately until the readiness event is
consumed by an attempt to read that fails with `WouldBlock` or
`Poll::Pending`.

## tokio::readable (function)

Waits for the socket to become readable.

This function is equivalent to `ready(Interest::READABLE)` and is usually
paired with `try_read()`.

### tokio::readable (function) › Cancel safety

This method is cancel safe. Once a readiness event occurs, the method
will continue to return immediately until the readiness event is
consumed by an attempt to read that fails with `WouldBlock` or
`Poll::Pending`.

### tokio::readable (function) › Examples

```no_run
use tokio::net::TcpStream;
use std::error::Error;
use std::io;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // Connect to a peer
    let stream = TcpStream::connect("127.0.0.1:8080").await?;

    let mut msg = vec![0; 1024];

    loop {
        // Wait for the socket to be readable
        stream.readable().await?;

        // Try to read data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match stream.try_read(&mut msg) {
            Ok(n) => {
                msg.truncate(n);
                break;
            }
            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    println!("GOT = {:?}", msg);
    Ok(())
}
```

## tokio::readable (function)

Waits for the socket to become readable.

This function is equivalent to `ready(Interest::READABLE)` and is usually
paired with `try_read()`.

### tokio::readable (function) › Cancel safety

This method is cancel safe. Once a readiness event occurs, the method
will continue to return immediately until the readiness event is
consumed by an attempt to read that fails with `WouldBlock` or
`Poll::Pending`.

### tokio::readable (function) › Examples

```no_run
use tokio::net::UnixStream;
use std::error::Error;
use std::io;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // Connect to a peer
    let dir = tempfile::tempdir().unwrap();
    let bind_path = dir.path().join("bind_path");
    let stream = UnixStream::connect(bind_path).await?;

    let mut msg = vec![0; 1024];

    loop {
        // Wait for the socket to be readable
        stream.readable().await?;

        // Try to read data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match stream.try_read(&mut msg) {
            Ok(n) => {
                msg.truncate(n);
                break;
            }
            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    println!("GOT = {:?}", msg);
    Ok(())
}
```

## tokio::readable (function)

Waits for the socket to become readable.

This function is equivalent to `ready(Interest::READABLE)` and is usually
paired with `try_read()`.

This function is also equivalent to [`TcpStream::ready`].

### tokio::readable (function) › Cancel safety

This method is cancel safe. Once a readiness event occurs, the method
will continue to return immediately until the readiness event is
consumed by an attempt to read that fails with `WouldBlock` or
`Poll::Pending`.

## tokio::readable (function)

Waits for the socket to become readable.

This function is equivalent to `ready(Interest::READABLE)` and is usually
paired with `try_read()`.

This function is also equivalent to [`TcpStream::ready`].

### tokio::readable (function) › Cancel safety

This method is cancel safe. Once a readiness event occurs, the method
will continue to return immediately until the readiness event is
consumed by an attempt to read that fails with `WouldBlock` or
`Poll::Pending`.

## tokio::readable (function)

Waits for the socket to become readable.

This function is equivalent to `ready(Interest::READABLE)` and is usually
paired with `try_recv()`.

The function may complete without the socket being readable. This is a
false-positive and attempting a `try_recv()` will return with
`io::ErrorKind::WouldBlock`.

### tokio::readable (function) › Cancel safety

This method is cancel safe. Once a readiness event occurs, the method
will continue to return immediately until the readiness event is
consumed by an attempt to read that fails with `WouldBlock` or
`Poll::Pending`.

### tokio::readable (function) › Examples

```no_run
use tokio::net::UdpSocket;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    // Connect to a peer
    let socket = UdpSocket::bind("127.0.0.1:8080").await?;
    socket.connect("127.0.0.1:8081").await?;

    loop {
        // Wait for the socket to be readable
        socket.readable().await?;

        // The buffer is **not** included in the async task and will
        // only exist on the stack.
        let mut buf = [0; 1024];

        // Try to recv data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match socket.try_recv(&mut buf) {
            Ok(n) => {
                println!("GOT {:?}", &buf[..n]);
                break;
            }
            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e);
            }
        }
    }

    Ok(())
}
```

## tokio::readable_mut (function)

Waits for the file descriptor to become readable, returning a
[`AsyncFdReadyMutGuard`] that must be dropped to resume read-readiness
polling.

This method takes `&mut self`, so it is possible to access the inner IO
resource mutably when handling the [`AsyncFdReadyMutGuard`].

### tokio::readable_mut (function) › Cancel safety

This method is cancel safe. Once a readiness event occurs, the method
will continue to return immediately until the readiness event is
consumed by an attempt to read or write that fails with `WouldBlock` or
`Poll::Pending`.

## tokio::reader (function)

Returns a reference to the inner reader.

## tokio::reader_mut (function)

Returns a mutable reference to the inner reader.

## tokio::reader_pin_mut (function)

Returns a pinned mutable reference to the inner reader.

## tokio::ready (function)

Get the [`Ready`] value associated with this guard.

This method will return the empty readiness state if
[`AsyncFdReadyGuard::clear_ready`] has been called on
the guard.

[`Ready`]: crate::io::Ready

## tokio::ready (function)

Get the [`Ready`] value associated with this guard.

This method will return the empty readiness state if
[`AsyncFdReadyGuard::clear_ready`] has been called on
the guard.

[`Ready`]: super::Ready

## tokio::ready (function)

Wait for any of the requested ready states.

This function is usually paired with [`try_read()`]. It can be used instead
of [`readable()`] to check the returned ready set for [`Ready::READABLE`]
and [`Ready::READ_CLOSED`] events.

The function may complete without the socket being ready. This is a
false-positive and attempting an operation will return with
`io::ErrorKind::WouldBlock`. The function can also return with an empty
[`Ready`] set, so you should always check the returned value and possibly
wait again if the requested states are not set.

This function is equivalent to [`UnixStream::ready`].

[`try_read()`]: Self::try_read
[`readable()`]: Self::readable

### tokio::ready (function) › Cancel safety

This method is cancel safe. Once a readiness event occurs, the method
will continue to return immediately until the readiness event is
consumed by an attempt to read or write that fails with `WouldBlock` or
`Poll::Pending`.

## tokio::ready (function)

Waits for any of the requested ready states, returning a
[`AsyncFdReadyGuard`] that must be dropped to resume
polling for the requested ready states.

The function may complete without the file descriptor being ready. This is a
false-positive and attempting an operation will return with
`io::ErrorKind::WouldBlock`. The function can also return with an empty
[`Ready`] set, so you should always check the returned value and possibly
wait again if the requested states are not set.

When an IO operation does return `io::ErrorKind::WouldBlock`, the readiness must be cleared.
When a combined interest is used, it is important to clear only the readiness
that is actually observed to block. For instance when the combined
interest `Interest::READABLE | Interest::WRITABLE` is used, and a read blocks, only
read readiness should be cleared using the [`AsyncFdReadyGuard::clear_ready_matching`] method:
`guard.clear_ready_matching(Ready::READABLE)`.
Also clearing the write readiness in this case would be incorrect. The [`AsyncFdReadyGuard::clear_ready`]
method clears all readiness flags.

This method takes `&self`, so it is possible to call this method
concurrently with other methods on this struct. This method only
provides shared access to the inner IO resource when handling the
[`AsyncFdReadyGuard`].

### tokio::ready (function) › Examples

Concurrently read and write to a [`std::net::TcpStream`] on the same task without
splitting.

```no_run
use std::error::Error;
use std::io;
use std::io::{Read, Write};
use std::net::TcpStream;
use tokio::io::unix::AsyncFd;
use tokio::io::{Interest, Ready};

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let stream = TcpStream::connect("127.0.0.1:8080")?;
    stream.set_nonblocking(true)?;
    let stream = AsyncFd::new(stream)?;

    loop {
        let mut guard = stream
            .ready(Interest::READABLE | Interest::WRITABLE)
            .await?;

        if guard.ready().is_readable() {
            let mut data = vec![0; 1024];
            // Try to read data, this may still fail with `WouldBlock`
            // if the readiness event is a false positive.
            match stream.get_ref().read(&mut data) {
                Ok(n) => {
                    println!("read {} bytes", n);
                }
                Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                    // a read has blocked, but a write might still succeed.
                    // clear only the read readiness.
                    guard.clear_ready_matching(Ready::READABLE);
                    continue;
                }
                Err(e) => {
                    return Err(e.into());
                }
            }
        }

        if guard.ready().is_writable() {
            // Try to write data, this may still fail with `WouldBlock`
            // if the readiness event is a false positive.
            match stream.get_ref().write(b"hello world") {
                Ok(n) => {
                    println!("write {} bytes", n);
                }
                Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                    // a write has blocked, but a read might still succeed.
                    // clear only the write readiness.
                    guard.clear_ready_matching(Ready::WRITABLE);
                    continue;
                }
                Err(e) => {
                    return Err(e.into());
                }
            }
        }
    }
}
```

## tokio::ready (function)

Waits for any of the requested ready states.

This function can be used instead of [`readable()`] to check the returned
ready set for [`Ready::READABLE`] and [`Ready::READ_CLOSED`] events.

The function may complete without the pipe being ready. This is a
false-positive and attempting an operation will return with
`io::ErrorKind::WouldBlock`. The function can also return with an empty
[`Ready`] set, so you should always check the returned value and possibly
wait again if the requested states are not set.

[`readable()`]: Self::readable

### tokio::ready (function) › Cancel safety

This method is cancel safe. Once a readiness event occurs, the method
will continue to return immediately until the readiness event is
consumed by an attempt to read that fails with `WouldBlock` or
`Poll::Pending`.

## tokio::ready (function)

Waits for any of the requested ready states.

This function can be used instead of [`writable()`] to check the returned
ready set for [`Ready::WRITABLE`] and [`Ready::WRITE_CLOSED`] events.

The function may complete without the pipe being ready. This is a
false-positive and attempting an operation will return with
`io::ErrorKind::WouldBlock`. The function can also return with an empty
[`Ready`] set, so you should always check the returned value and possibly
wait again if the requested states are not set.

[`writable()`]: Self::writable

### tokio::ready (function) › Cancel safety

This method is cancel safe. Once a readiness event occurs, the method
will continue to return immediately until the readiness event is
consumed by an attempt to write that fails with `WouldBlock` or
`Poll::Pending`.

## tokio::ready (function)

Waits for any of the requested ready states.

This function is usually paired with [`try_read()`]. It can be used instead
of [`readable()`] to check the returned ready set for [`Ready::READABLE`]
and [`Ready::READ_CLOSED`] events.

The function may complete without the socket being ready. This is a
false-positive and attempting an operation will return with
`io::ErrorKind::WouldBlock`. The function can also return with an empty
[`Ready`] set, so you should always check the returned value and possibly
wait again if the requested states are not set.

This function is equivalent to [`TcpStream::ready`].

[`try_read()`]: Self::try_read
[`readable()`]: Self::readable

### tokio::ready (function) › Cancel safety

This method is cancel safe. Once a readiness event occurs, the method
will continue to return immediately until the readiness event is
consumed by an attempt to read or write that fails with `WouldBlock` or
`Poll::Pending`.

## tokio::ready (function)

Waits for any of the requested ready states.

This function is usually paired with [`try_read()`]. It can be used instead
of [`readable()`] to check the returned ready set for [`Ready::READABLE`]
and [`Ready::READ_CLOSED`] events.

The function may complete without the socket being ready. This is a
false-positive and attempting an operation will return with
`io::ErrorKind::WouldBlock`. The function can also return with an empty
[`Ready`] set, so you should always check the returned value and possibly
wait again if the requested states are not set.

This function is equivalent to [`TcpStream::ready`].

[`try_read()`]: Self::try_read
[`readable()`]: Self::readable

### tokio::ready (function) › Cancel safety

This method is cancel safe. Once a readiness event occurs, the method
will continue to return immediately until the readiness event is
consumed by an attempt to read or write that fails with `WouldBlock` or
`Poll::Pending`.

## tokio::ready (function)

Waits for any of the requested ready states.

This function is usually paired with [`try_read()`]. It can be used instead
of [`readable()`] to check the returned ready set for [`Ready::READABLE`]
and [`Ready::READ_CLOSED`] events.

The function may complete without the socket being ready. This is a
false-positive and attempting an operation will return with
`io::ErrorKind::WouldBlock`. The function can also return with an empty
[`Ready`] set, so you should always check the returned value and possibly
wait again if the requested states are not set.

This function is equivalent to [`UnixStream::ready`].

[`try_read()`]: Self::try_read
[`readable()`]: Self::readable

### tokio::ready (function) › Cancel safety

This method is cancel safe. Once a readiness event occurs, the method
will continue to return immediately until the readiness event is
consumed by an attempt to read or write that fails with `WouldBlock` or
`Poll::Pending`.

## tokio::ready (function)

Waits for any of the requested ready states.

This function is usually paired with [`try_write()`]. It can be used instead
of [`writable()`] to check the returned ready set for [`Ready::WRITABLE`]
and [`Ready::WRITE_CLOSED`] events.

The function may complete without the socket being ready. This is a
false-positive and attempting an operation will return with
`io::ErrorKind::WouldBlock`. The function can also return with an empty
[`Ready`] set, so you should always check the returned value and possibly
wait again if the requested states are not set.

This function is equivalent to [`TcpStream::ready`].

[`try_write()`]: Self::try_write
[`writable()`]: Self::writable

### tokio::ready (function) › Cancel safety

This method is cancel safe. Once a readiness event occurs, the method
will continue to return immediately until the readiness event is
consumed by an attempt to read or write that fails with `WouldBlock` or
`Poll::Pending`.

## tokio::ready (function)

Waits for any of the requested ready states.

This function is usually paired with [`try_write()`]. It can be used instead
of [`writable()`] to check the returned ready set for [`Ready::WRITABLE`]
and [`Ready::WRITE_CLOSED`] events.

The function may complete without the socket being ready. This is a
false-positive and attempting an operation will return with
`io::ErrorKind::WouldBlock`. The function can also return with an empty
[`Ready`] set, so you should always check the returned value and possibly
wait again if the requested states are not set.

This function is equivalent to [`TcpStream::ready`].

[`try_write()`]: Self::try_write
[`writable()`]: Self::writable

### tokio::ready (function) › Cancel safety

This method is cancel safe. Once a readiness event occurs, the method
will continue to return immediately until the readiness event is
consumed by an attempt to read or write that fails with `WouldBlock` or
`Poll::Pending`.

## tokio::ready (function)

Waits for any of the requested ready states.

This function is usually paired with [`try_write()`]. It can be used instead
of [`writable()`] to check the returned ready set for [`Ready::WRITABLE`]
and [`Ready::WRITE_CLOSED`] events.

The function may complete without the socket being ready. This is a
false-positive and attempting an operation will return with
`io::ErrorKind::WouldBlock`. The function can also return with an empty
[`Ready`] set, so you should always check the returned value and possibly
wait again if the requested states are not set.

This function is equivalent to [`UnixStream::ready`].

[`try_write()`]: Self::try_write
[`writable()`]: Self::writable

### tokio::ready (function) › Cancel safety

This method is cancel safe. Once a readiness event occurs, the method
will continue to return immediately until the readiness event is
consumed by an attempt to read or write that fails with `WouldBlock` or
`Poll::Pending`.

## tokio::ready (function)

Waits for any of the requested ready states.

This function is usually paired with [`try_write()`]. It can be used instead
of [`writable()`] to check the returned ready set for [`Ready::WRITABLE`]
and [`Ready::WRITE_CLOSED`] events.

The function may complete without the socket being ready. This is a
false-positive and attempting an operation will return with
`io::ErrorKind::WouldBlock`. The function can also return with an empty
[`Ready`] set, so you should always check the returned value and possibly
wait again if the requested states are not set.

This function is equivalent to [`UnixStream::ready`].

[`try_write()`]: Self::try_write
[`writable()`]: Self::writable

### tokio::ready (function) › Cancel safety

This method is cancel safe. Once a readiness event occurs, the method
will continue to return immediately until the readiness event is
consumed by an attempt to read or write that fails with `WouldBlock` or
`Poll::Pending`.

## tokio::ready (function)

Waits for any of the requested ready states.

This function is usually paired with `try_read()` or `try_write()`. It
can be used to concurrently read / write to the same pipe on a single
task without splitting the pipe.

The function may complete without the pipe being ready. This is a
false-positive and attempting an operation will return with
`io::ErrorKind::WouldBlock`. The function can also return with an empty
[`Ready`] set, so you should always check the returned value and possibly
wait again if the requested states are not set.

### tokio::ready (function) › Examples

Concurrently read and write to the pipe on the same task without
splitting.

```no_run
use tokio::io::Interest;
use tokio::net::windows::named_pipe;
use std::error::Error;
use std::io;

const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-client-ready";

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let client = named_pipe::ClientOptions::new().open(PIPE_NAME)?;

    loop {
        let ready = client.ready(Interest::READABLE | Interest::WRITABLE).await?;

        if ready.is_readable() {
            let mut data = vec![0; 1024];
            // Try to read data, this may still fail with `WouldBlock`
            // if the readiness event is a false positive.
            match client.try_read(&mut data) {
                Ok(n) => {
                    println!("read {} bytes", n);
                }
                Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
                    continue;
                }
                Err(e) => {
                    return Err(e.into());
                }
            }
        }

        if ready.is_writable() {
            // Try to write data, this may still fail with `WouldBlock`
            // if the readiness event is a false positive.
            match client.try_write(b"hello world") {
                Ok(n) => {
                    println!("write {} bytes", n);
                }
                Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
                    continue;
                }
                Err(e) => {
                    return Err(e.into());
                }
            }
        }
    }
}
```

## tokio::ready (function)

Waits for any of the requested ready states.

This function is usually paired with `try_read()` or `try_write()`. It
can be used to concurrently read / write to the same pipe on a single
task without splitting the pipe.

The function may complete without the pipe being ready. This is a
false-positive and attempting an operation will return with
`io::ErrorKind::WouldBlock`. The function can also return with an empty
[`Ready`] set, so you should always check the returned value and possibly
wait again if the requested states are not set.

### tokio::ready (function) › Examples

Concurrently read and write to the pipe on the same task without
splitting.

```no_run
use tokio::io::Interest;
use tokio::net::windows::named_pipe;
use std::error::Error;
use std::io;

const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-server-ready";

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let server = named_pipe::ServerOptions::new()
        .create(PIPE_NAME)?;

    loop {
        let ready = server.ready(Interest::READABLE | Interest::WRITABLE).await?;

        if ready.is_readable() {
            let mut data = vec![0; 1024];
            // Try to read data, this may still fail with `WouldBlock`
            // if the readiness event is a false positive.
            match server.try_read(&mut data) {
                Ok(n) => {
                    println!("read {} bytes", n);
                }
                Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
                    continue;
                }
                Err(e) => {
                    return Err(e.into());
                }
            }
        }

        if ready.is_writable() {
            // Try to write data, this may still fail with `WouldBlock`
            // if the readiness event is a false positive.
            match server.try_write(b"hello world") {
                Ok(n) => {
                    println!("write {} bytes", n);
                }
                Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
                    continue;
                }
                Err(e) => {
                    return Err(e.into());
                }
            }
        }
    }
}
```

## tokio::ready (function)

Waits for any of the requested ready states.

This function is usually paired with `try_read()` or `try_write()`. It
can be used to concurrently read / write to the same socket on a single
task without splitting the socket.

The function may complete without the socket being ready. This is a
false-positive and attempting an operation will return with
`io::ErrorKind::WouldBlock`. The function can also return with an empty
[`Ready`] set, so you should always check the returned value and possibly
wait again if the requested states are not set.

### tokio::ready (function) › Cancel safety

This method is cancel safe. Once a readiness event occurs, the method
will continue to return immediately until the readiness event is
consumed by an attempt to read or write that fails with `WouldBlock` or
`Poll::Pending`.

### tokio::ready (function) › Examples

Concurrently read and write to the stream on the same task without
splitting.

```no_run
use tokio::io::Interest;
use tokio::net::TcpStream;
use std::error::Error;
use std::io;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let stream = TcpStream::connect("127.0.0.1:8080").await?;

    loop {
        let ready = stream.ready(Interest::READABLE | Interest::WRITABLE).await?;

        if ready.is_readable() {
            let mut data = vec![0; 1024];
            // Try to read data, this may still fail with `WouldBlock`
            // if the readiness event is a false positive.
            match stream.try_read(&mut data) {
                Ok(n) => {
                    println!("read {} bytes", n);
                }
                Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                    continue;
                }
                Err(e) => {
                    return Err(e.into());
                }
            }

        }

        if ready.is_writable() {
            // Try to write data, this may still fail with `WouldBlock`
            // if the readiness event is a false positive.
            match stream.try_write(b"hello world") {
                Ok(n) => {
                    println!("write {} bytes", n);
                }
                Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                    continue
                }
                Err(e) => {
                    return Err(e.into());
                }
            }
        }
    }
}
```

## tokio::ready (function)

Waits for any of the requested ready states.

This function is usually paired with `try_read()` or `try_write()`. It
can be used to concurrently read / write to the same socket on a single
task without splitting the socket.

The function may complete without the socket being ready. This is a
false-positive and attempting an operation will return with
`io::ErrorKind::WouldBlock`. The function can also return with an empty
[`Ready`] set, so you should always check the returned value and possibly
wait again if the requested states are not set.

### tokio::ready (function) › Cancel safety

This method is cancel safe. Once a readiness event occurs, the method
will continue to return immediately until the readiness event is
consumed by an attempt to read or write that fails with `WouldBlock` or
`Poll::Pending`.

### tokio::ready (function) › Examples

Concurrently read and write to the stream on the same task without
splitting.

```no_run
use tokio::io::Interest;
use tokio::net::UnixStream;
use std::error::Error;
use std::io;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let dir = tempfile::tempdir().unwrap();
    let bind_path = dir.path().join("bind_path");
    let stream = UnixStream::connect(bind_path).await?;

    loop {
        let ready = stream.ready(Interest::READABLE | Interest::WRITABLE).await?;

        if ready.is_readable() {
            let mut data = vec![0; 1024];
            // Try to read data, this may still fail with `WouldBlock`
            // if the readiness event is a false positive.
            match stream.try_read(&mut data) {
                Ok(n) => {
                    println!("read {} bytes", n);
                }
                Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                    continue;
                }
                Err(e) => {
                    return Err(e.into());
                }
            }

        }

        if ready.is_writable() {
            // Try to write data, this may still fail with `WouldBlock`
            // if the readiness event is a false positive.
            match stream.try_write(b"hello world") {
                Ok(n) => {
                    println!("write {} bytes", n);
                }
                Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                    continue;
                }
                Err(e) => {
                    return Err(e.into());
                }
            }
        }
    }
}
```

## tokio::ready (function)

Waits for any of the requested ready states.

This function is usually paired with `try_recv()` or `try_send()`. It
can be used to concurrently `recv` / `send` to the same socket on a single
task without splitting the socket.

The function may complete without the socket being ready. This is a
false-positive and attempting an operation will return with
`io::ErrorKind::WouldBlock`. The function can also return with an empty
[`Ready`] set, so you should always check the returned value and possibly
wait again if the requested states are not set.

### tokio::ready (function) › Cancel safety

This method is cancel safe. Once a readiness event occurs, the method
will continue to return immediately until the readiness event is
consumed by an attempt to read or write that fails with `WouldBlock` or
`Poll::Pending`.

### tokio::ready (function) › Examples

Concurrently receive from and send to the socket on the same task
without splitting.

```no_run
use tokio::io::{self, Interest};
use tokio::net::UdpSocket;

#[tokio::main]
async fn main() -> io::Result<()> {
    let socket = UdpSocket::bind("127.0.0.1:8080").await?;
    socket.connect("127.0.0.1:8081").await?;

    loop {
        let ready = socket.ready(Interest::READABLE | Interest::WRITABLE).await?;

        if ready.is_readable() {
            // The buffer is **not** included in the async task and will only exist
            // on the stack.
            let mut data = [0; 1024];
            match socket.try_recv(&mut data[..]) {
                Ok(n) => {
                    println!("received {:?}", &data[..n]);
                }
                // False-positive, continue
                Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {}
                Err(e) => {
                    return Err(e);
                }
            }
        }

        if ready.is_writable() {
            // Write some data
            match socket.try_send(b"hello world") {
                Ok(n) => {
                    println!("sent {} bytes", n);
                }
                // False-positive, continue
                Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {}
                Err(e) => {
                    return Err(e);
                }
            }
        }
    }
}
```

## tokio::ready_mut (function)

Waits for any of the requested ready states, returning a
[`AsyncFdReadyMutGuard`] that must be dropped to resume
polling for the requested ready states.

The function may complete without the file descriptor being ready. This is a
false-positive and attempting an operation will return with
`io::ErrorKind::WouldBlock`. The function can also return with an empty
[`Ready`] set, so you should always check the returned value and possibly
wait again if the requested states are not set.

When an IO operation does return `io::ErrorKind::WouldBlock`, the readiness must be cleared.
When a combined interest is used, it is important to clear only the readiness
that is actually observed to block. For instance when the combined
interest `Interest::READABLE | Interest::WRITABLE` is used, and a read blocks, only
read readiness should be cleared using the [`AsyncFdReadyMutGuard::clear_ready_matching`] method:
`guard.clear_ready_matching(Ready::READABLE)`.
Also clearing the write readiness in this case would be incorrect.
The [`AsyncFdReadyMutGuard::clear_ready`] method clears all readiness flags.

This method takes `&mut self`, so it is possible to access the inner IO
resource mutably when handling the [`AsyncFdReadyMutGuard`].

### tokio::ready_mut (function) › Examples

Concurrently read and write to a [`std::net::TcpStream`] on the same task without
splitting.

```no_run
use std::error::Error;
use std::io;
use std::io::{Read, Write};
use std::net::TcpStream;
use tokio::io::unix::AsyncFd;
use tokio::io::{Interest, Ready};

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let stream = TcpStream::connect("127.0.0.1:8080")?;
    stream.set_nonblocking(true)?;
    let mut stream = AsyncFd::new(stream)?;

    loop {
        let mut guard = stream
            .ready_mut(Interest::READABLE | Interest::WRITABLE)
            .await?;

        if guard.ready().is_readable() {
            let mut data = vec![0; 1024];
            // Try to read data, this may still fail with `WouldBlock`
            // if the readiness event is a false positive.
            match guard.get_inner_mut().read(&mut data) {
                Ok(n) => {
                    println!("read {} bytes", n);
                }
                Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                    // a read has blocked, but a write might still succeed.
                    // clear only the read readiness.
                    guard.clear_ready_matching(Ready::READABLE);
                    continue;
                }
                Err(e) => {
                    return Err(e.into());
                }
            }
        }

        if guard.ready().is_writable() {
            // Try to write data, this may still fail with `WouldBlock`
            // if the readiness event is a false positive.
            match guard.get_inner_mut().write(b"hello world") {
                Ok(n) => {
                    println!("write {} bytes", n);
                }
                Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                    // a write has blocked, but a read might still succeed.
                    // clear only the write readiness.
                    guard.clear_ready_matching(Ready::WRITABLE);
                    continue;
                }
                Err(e) => {
                    return Err(e.into());
                }
            }
        }
    }
}
```

## tokio::receiver_count (function)

Returns the number of active receivers.

An active receiver is a [`Receiver`] handle returned from [`channel`] or
[`subscribe`]. These are the handles that will receive values sent on
this [`Sender`].

### tokio::receiver_count (function) › Note

It is not guaranteed that a sent message will reach this number of
receivers. Active receivers may never call [`recv`] again before
dropping.

[`recv`]: crate::sync::broadcast::Receiver::recv
[`Receiver`]: crate::sync::broadcast::Receiver
[`Sender`]: crate::sync::broadcast::Sender
[`subscribe`]: crate::sync::broadcast::Sender::subscribe
[`channel`]: crate::sync::broadcast::channel

### tokio::receiver_count (function) › Examples

```
use tokio::sync::broadcast;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, _rx1) = broadcast::channel(16);

assert_eq!(1, tx.receiver_count());

let mut _rx2 = tx.subscribe();

assert_eq!(2, tx.receiver_count());

tx.send(10).unwrap();
# }
```

## tokio::receiver_count (function)

Returns the number of receivers that currently exist.

### tokio::receiver_count (function) › Examples

```
use tokio::sync::watch;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, rx1) = watch::channel("hello");

assert_eq!(1, tx.receiver_count());

let mut _rx2 = rx1.clone();

assert_eq!(2, tx.receiver_count());
# }
```

## tokio::recursive (function)

Indicates whether to create directories recursively (including all parent directories).
Parents that do not exist are created with the same security and permissions settings.

This option defaults to `false`.

This is an async version of [`std::fs::DirBuilder::recursive`].

### tokio::recursive (function) › Examples

```no_run
use tokio::fs::DirBuilder;

let mut builder = DirBuilder::new();
builder.recursive(true);
```

## tokio::recv (function)

Receives a single datagram message on the socket from the remote address
to which it is connected. On success, returns the number of bytes read.

The function must be called with valid byte array `buf` of sufficient
size to hold the message bytes. If a message is too long to fit in the
supplied buffer, excess bytes may be discarded.

The [`connect`] method will connect this socket to a remote address.
This method will fail if the socket is not connected.

### tokio::recv (function) › Cancel safety

This method is cancel safe. If `recv` is used as a branch in
[`tokio::select!`](crate::select) and another branch
completes first, it is guaranteed that no messages were received on this
socket.

[`connect`]: method@Self::connect

```no_run
use tokio::net::UdpSocket;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    // Bind socket
    let socket = UdpSocket::bind("127.0.0.1:8080").await?;
    socket.connect("127.0.0.1:8081").await?;

    let mut buf = vec![0; 10];
    let n = socket.recv(&mut buf).await?;

    println!("received {} bytes {:?}", n, &buf[..n]);

    Ok(())
}
```

## tokio::recv (function)

Receives the next signal notification event.

Although this returns `Option<()>`, it will never actually return `None`.
This was accidentally exposed and would be a breaking change to be removed.

### tokio::recv (function) › Cancel safety

This method is cancel safe. If you use it as a branch in
[`tokio::select!`](crate::select) and another branch
completes first, then it is guaranteed that no signal is lost.

### tokio::recv (function) › Examples

Wait for `SIGHUP`

```rust,no_run
use tokio::signal::unix::{signal, SignalKind};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // An infinite stream of hangup signals.
    let mut stream = signal(SignalKind::hangup())?;

    // Print whenever a HUP signal is received
    loop {
        stream.recv().await;
        println!("got signal HUP");
    }
}
```

## tokio::recv (function)

Receives the next signal notification event.

Although this returns `Option<()>`, it will never actually return `None`.
This was accidentally exposed and would be a breaking change to be removed.

### tokio::recv (function) › Examples

```rust,no_run
use tokio::signal::windows::ctrl_break;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // A listener of CTRL-BREAK events.
    let mut signal = ctrl_break()?;

    // Print whenever a CTRL-BREAK event is received.
    loop {
        signal.recv().await;
        println!("got signal CTRL-BREAK");
    }
}
```

## tokio::recv (function)

Receives the next signal notification event.

Although this returns `Option<()>`, it will never actually return `None`.
This was accidentally exposed and would be a breaking change to be removed.

### tokio::recv (function) › Examples

```rust,no_run
use tokio::signal::windows::ctrl_c;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut signal = ctrl_c()?;

    // Print whenever a CTRL-C event is received.
    for countdown in (0..3).rev() {
        signal.recv().await;
        println!("got CTRL-C. {} more to exit", countdown);
    }

    Ok(())
}
```

## tokio::recv (function)

Receives the next signal notification event.

Although this returns `Option<()>`, it will never actually return `None`.
This was accidentally exposed and would be a breaking change to be removed.

### tokio::recv (function) › Examples

```rust,no_run
use tokio::signal::windows::ctrl_close;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // A listener of CTRL-CLOSE events.
    let mut signal = ctrl_close()?;

    // Print whenever a CTRL-CLOSE event is received.
    signal.recv().await;
    println!("got CTRL-CLOSE. Cleaning up before exiting");

    Ok(())
}
```

## tokio::recv (function)

Receives the next signal notification event.

Although this returns `Option<()>`, it will never actually return `None`.
This was accidentally exposed and would be a breaking change to be removed.

### tokio::recv (function) › Examples

```rust,no_run
use tokio::signal::windows::ctrl_logoff;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // An listener of CTRL-LOGOFF events.
    let mut signal = ctrl_logoff()?;

    // Print whenever a CTRL-LOGOFF event is received.
    signal.recv().await;
    println!("got CTRL-LOGOFF. Cleaning up before exiting");

    Ok(())
}
```

## tokio::recv (function)

Receives the next signal notification event.

Although this returns `Option<()>`, it will never actually return `None`.
This was accidentally exposed and would be a breaking change to be removed.

### tokio::recv (function) › Examples

```rust,no_run
use tokio::signal::windows::ctrl_shutdown;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // A listener of CTRL-SHUTDOWN events.
    let mut signal = ctrl_shutdown()?;

    // Print whenever a CTRL-SHUTDOWN event is received.
    signal.recv().await;
    println!("got CTRL-SHUTDOWN. Cleaning up before exiting");

    Ok(())
}
```

## tokio::recv (function)

Receives the next value for this receiver.

Each [`Receiver`] handle will receive a clone of all values sent
**after** it has subscribed.

`Err(RecvError::Closed)` is returned when all `Sender` halves have
dropped, indicating that no further values can be sent on the channel.

If the [`Receiver`] handle falls behind, once the channel is full, newly
sent values overwrite old values in the ring buffer. The next call to
[`recv`] then returns `Err(RecvError::Lagged(n))`, where `n` is the
number of overwritten messages the receiver missed. The receiver stays
subscribed; its internal cursor is advanced to the oldest value still
held by the channel. A subsequent call to [`recv`] returns that value,
unless further sends overwrite it before the receiver reads it. See
[lagging](self#lagging) for details.

### tokio::recv (function) › Cancel safety

This method is cancel safe. If `recv` is used as a branch in
[`tokio::select!`](crate::select) and another branch
completes first, it is guaranteed that no messages were received on this
channel.

[`Receiver`]: crate::sync::broadcast::Receiver
[`recv`]: crate::sync::broadcast::Receiver::recv

### tokio::recv (function) › Examples

```
use tokio::sync::broadcast;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx1) = broadcast::channel(16);
let mut rx2 = tx.subscribe();

tokio::spawn(async move {
    assert_eq!(rx1.recv().await.unwrap(), 10);
    assert_eq!(rx1.recv().await.unwrap(), 20);
});

tokio::spawn(async move {
    assert_eq!(rx2.recv().await.unwrap(), 10);
    assert_eq!(rx2.recv().await.unwrap(), 20);
});

tx.send(10).unwrap();
tx.send(20).unwrap();
# }
```

Handling lag

```
use tokio::sync::broadcast;
use tokio::sync::broadcast::error::RecvError;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = broadcast::channel(2);

tx.send(10).unwrap();
tx.send(20).unwrap();
tx.send(30).unwrap();

// One message was overwritten before this receiver could read it.
assert!(matches!(rx.recv().await, Err(RecvError::Lagged(1))));

// Resume from the oldest retained message, or abort the task instead.
assert_eq!(20, rx.recv().await.unwrap());
assert_eq!(30, rx.recv().await.unwrap());
# }
```

## tokio::recv (function)

Receives the next value for this receiver.

This method returns `None` if the channel has been closed and there are
no remaining messages in the channel's buffer. This indicates that no
further values can ever be received from this `Receiver`. The channel is
closed when all senders have been dropped, or when [`close`] is called.

If there are no messages in the channel's buffer, but the channel has
not yet been closed, this method will sleep until a message is sent or
the channel is closed.

### tokio::recv (function) › Cancel safety

This method is cancel safe. If `recv` is used as a branch in
[`tokio::select!`](crate::select) and another branch completes first,
it is guaranteed that no messages were received on this
channel.

[`close`]: Self::close

### tokio::recv (function) › Examples

```
use tokio::sync::mpsc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = mpsc::unbounded_channel();

tokio::spawn(async move {
    tx.send("hello").unwrap();
});

assert_eq!(Some("hello"), rx.recv().await);
assert_eq!(None, rx.recv().await);
# }
```

Values are buffered:

```
use tokio::sync::mpsc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = mpsc::unbounded_channel();

tx.send("hello").unwrap();
tx.send("world").unwrap();

assert_eq!(Some("hello"), rx.recv().await);
assert_eq!(Some("world"), rx.recv().await);
# }
```

## tokio::recv (function)

Receives the next value for this receiver.

This method returns `None` if the channel has been closed and there are
no remaining messages in the channel's buffer. This indicates that no
further values can ever be received from this `Receiver`. The channel is
closed when all senders have been dropped, or when [`close`] is called.

If there are no messages in the channel's buffer, but the channel has
not yet been closed, this method will sleep until a message is sent or
the channel is closed.  Note that if [`close`] is called, but there are
still outstanding [`Permits`] from before it was closed, the channel is
not considered closed by `recv` until the permits are released.

### tokio::recv (function) › Cancel safety

This method is cancel safe. If `recv` is used as a branch in
[`tokio::select!`](crate::select) and another branch completes first,
it is guaranteed that no messages were received on this
channel.

[`close`]: Self::close
[`Permits`]: struct@crate::sync::mpsc::Permit

### tokio::recv (function) › Examples

```
use tokio::sync::mpsc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = mpsc::channel(100);

tokio::spawn(async move {
    tx.send("hello").await.unwrap();
});

assert_eq!(Some("hello"), rx.recv().await);
assert_eq!(None, rx.recv().await);
# }
```

Values are buffered:

```
use tokio::sync::mpsc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = mpsc::channel(100);

tx.send("hello").await.unwrap();
tx.send("world").await.unwrap();

assert_eq!(Some("hello"), rx.recv().await);
assert_eq!(Some("world"), rx.recv().await);
# }
```

## tokio::recv_buf (function)

Receives a single datagram message on the socket from the remote address
to which it is connected, advancing the buffer's internal cursor,
returning how many bytes were read.

This method must be called with valid byte array `buf` of sufficient size
to hold the message bytes. If a message is too long to fit in the
supplied buffer, excess bytes may be discarded.

This method can be used even if `buf` is uninitialized.

### tokio::recv_buf (function) › Examples

```no_run
use tokio::net::UdpSocket;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    // Connect to a peer
    let socket = UdpSocket::bind("127.0.0.1:8080").await?;
    socket.connect("127.0.0.1:8081").await?;

    let mut buf = Vec::with_capacity(512);
    let len = socket.recv_buf(&mut buf).await?;

    println!("received {} bytes {:?}", len, &buf[..len]);

    Ok(())
}
```

## tokio::recv_buf_from (function)

Receives a single datagram message on the socket, advancing the
buffer's internal cursor, returning how many bytes were read and the origin.

This method must be called with valid byte array `buf` of sufficient size
to hold the message bytes. If a message is too long to fit in the
supplied buffer, excess bytes may be discarded.

This method can be used even if `buf` is uninitialized.

### tokio::recv_buf_from (function) › Notes
Note that the socket address **cannot** be implicitly trusted, because it is relatively
trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
Because UDP is stateless and does not validate the origin of a packet,
the attacker does not need to be able to intercept traffic in order to interfere.
It is important to be aware of this when designing your application-level protocol.

[packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection

### tokio::recv_buf_from (function) › Examples

```no_run
use tokio::net::UdpSocket;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    // Connect to a peer
    let socket = UdpSocket::bind("127.0.0.1:8080").await?;
    socket.connect("127.0.0.1:8081").await?;

    let mut buf = Vec::with_capacity(512);
    let (len, addr) = socket.recv_buf_from(&mut buf).await?;

    println!("received {:?} bytes from {:?}", len, addr);

    Ok(())
}
```

## tokio::recv_buffer_size (function)

Returns the size of the TCP receive buffer for this socket.

On most operating systems, this is the value of the `SO_RCVBUF` socket
option.

Note that if [`set_recv_buffer_size`] has been called on this socket
previously, the value returned by this function may not be the same as
the argument provided to `set_recv_buffer_size`. This is for the
following reasons:

* Most operating systems have minimum and maximum allowed sizes for the
  receive buffer, and will clamp the provided value if it is below the
  minimum or above the maximum. The minimum and maximum buffer sizes are
  OS-dependent.
* Linux will double the buffer size to account for internal bookkeeping
  data, and returns the doubled value from `getsockopt(2)`. As per `man
  7 socket`:
  > Sets or gets the maximum socket send buffer in bytes. The
  > kernel doubles this value (to allow space for bookkeeping
  > overhead) when it is set using `setsockopt(2)`, and this doubled
  > value is returned by `getsockopt(2)`.

[`set_recv_buffer_size`]: #method.set_recv_buffer_size

## tokio::recv_from (function)

Receives a single datagram message on the socket. On success, returns
the number of bytes read and the origin.

The function must be called with valid byte array `buf` of sufficient
size to hold the message bytes. If a message is too long to fit in the
supplied buffer, excess bytes may be discarded.

### tokio::recv_from (function) › Cancel safety

This method is cancel safe. If `recv_from` is used as a branch in
[`tokio::select!`](crate::select) and another branch
completes first, it is guaranteed that no messages were received on this
socket.

### tokio::recv_from (function) › Example

```no_run
use tokio::net::UdpSocket;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let socket = UdpSocket::bind("127.0.0.1:8080").await?;

    let mut buf = vec![0u8; 32];
    let (len, addr) = socket.recv_from(&mut buf).await?;

    println!("received {:?} bytes from {:?}", len, addr);

    Ok(())
}
```

### tokio::recv_from (function) › Notes
Note that the socket address **cannot** be implicitly trusted, because it is relatively
trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
Because UDP is stateless and does not validate the origin of a packet,
the attacker does not need to be able to intercept traffic in order to interfere.
It is important to be aware of this when designing your application-level protocol.

[packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection

## tokio::recv_many (function)

Receives the next values for this receiver and extends `buffer`.

This method extends `buffer` by no more than a fixed number of values
as specified by `limit`. If `limit` is zero, the function immediately
returns `0`. The return value is the number of values added to `buffer`.

For `limit > 0`, if there are no messages in the channel's queue, but
the channel has not yet been closed, this method will sleep until a
message is sent or the channel is closed. Note that if [`close`] is
called, but there are still outstanding [`Permits`] from before it was
closed, the channel is not considered closed by `recv_many` until the
permits are released.

For non-zero values of `limit`, this method will never return `0` unless
the channel has been closed and there are no remaining messages in the
channel's queue. This indicates that no further values can ever be
received from this `Receiver`. The channel is closed when all senders
have been dropped, or when [`close`] is called.

The capacity of `buffer` is increased as needed.

### tokio::recv_many (function) › Cancel safety

This method is cancel safe. If `recv_many` is used as a branch in
[`tokio::select!`](crate::select) and another branch completes first,
it is guaranteed that no messages were received on this
channel.

[`close`]: Self::close
[`Permits`]: struct@crate::sync::mpsc::Permit

### tokio::recv_many (function) › Examples

```
use tokio::sync::mpsc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let mut buffer: Vec<&str> = Vec::with_capacity(2);
let limit = 2;
let (tx, mut rx) = mpsc::channel(100);
let tx2 = tx.clone();
tx2.send("first").await.unwrap();
tx2.send("second").await.unwrap();
tx2.send("third").await.unwrap();

// Call `recv_many` to receive up to `limit` (2) values.
assert_eq!(2, rx.recv_many(&mut buffer, limit).await);
assert_eq!(vec!["first", "second"], buffer);

// If the buffer is full, the next call to `recv_many`
// reserves additional capacity.
assert_eq!(1, rx.recv_many(&mut buffer, 1).await);

tokio::spawn(async move {
    tx.send("fourth").await.unwrap();
});

// 'tx' is dropped, but `recv_many`
// is guaranteed not to return 0 as the channel
// is not yet closed.
assert_eq!(1, rx.recv_many(&mut buffer, 1).await);
assert_eq!(vec!["first", "second", "third", "fourth"], buffer);

// Once the last sender is dropped, the channel is
// closed and `recv_many` returns 0, capacity unchanged.
drop(tx2);
assert_eq!(0, rx.recv_many(&mut buffer, limit).await);
assert_eq!(vec!["first", "second", "third", "fourth"], buffer);
# }
```

## tokio::recv_many (function)

Receives the next values for this receiver and extends `buffer`.

This method extends `buffer` by no more than a fixed number of values
as specified by `limit`. If `limit` is zero, the function returns
immediately with `0`. The return value is the number of values added to
`buffer`.

For `limit > 0`, if there are no messages in the channel's queue,
but the channel has not yet been closed, this method will sleep
until a message is sent or the channel is closed.

For non-zero values of `limit`, this method will never return `0` unless
the channel has been closed and there are no remaining messages in the
channel's queue. This indicates that no further values can ever be
received from this `Receiver`. The channel is closed when all senders
have been dropped, or when [`close`] is called.

The capacity of `buffer` is increased as needed.

### tokio::recv_many (function) › Cancel safety

This method is cancel safe. If `recv_many` is used as a branch in
[`tokio::select!`](crate::select) and another branch completes first,
it is guaranteed that no messages were received on this
channel.

[`close`]: Self::close

### tokio::recv_many (function) › Examples

```
use tokio::sync::mpsc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let mut buffer: Vec<&str> = Vec::with_capacity(2);
let limit = 2;
let (tx, mut rx) = mpsc::unbounded_channel();
let tx2 = tx.clone();
tx2.send("first").unwrap();
tx2.send("second").unwrap();
tx2.send("third").unwrap();

// Call `recv_many` to receive up to `limit` (2) values.
assert_eq!(2, rx.recv_many(&mut buffer, limit).await);
assert_eq!(vec!["first", "second"], buffer);

// If the buffer is full, the next call to `recv_many`
// reserves additional capacity.
assert_eq!(1, rx.recv_many(&mut buffer, limit).await);

tokio::spawn(async move {
    tx.send("fourth").unwrap();
});

// 'tx' is dropped, but `recv_many`
// is guaranteed not to return 0 as the channel
// is not yet closed.
assert_eq!(1, rx.recv_many(&mut buffer, limit).await);
assert_eq!(vec!["first", "second", "third", "fourth"], buffer);

// Once the last sender is dropped, the channel is
// closed and `recv_many` returns 0, capacity unchanged.
drop(tx2);
assert_eq!(0, rx.recv_many(&mut buffer, limit).await);
assert_eq!(vec!["first", "second", "third", "fourth"], buffer);
# }
```

## tokio::register (function)

Registers this AIO event source with Tokio's reactor.

### tokio::register (function) › Safety

It's memory-safe, but not I/O safe.  If the file referenced by `kq` gets dropped, then this
source may end up notifying the wrong file.

## tokio::register_borrowed (function)

Registers this AIO event source with Tokio's reactor.

## tokio::reject_remote_clients (function)

Indicates whether this server can accept remote clients or not. Remote
clients are disabled by default.

This corresponds to setting [`PIPE_REJECT_REMOTE_CLIENTS`].

[`PIPE_REJECT_REMOTE_CLIENTS`]: https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createnamedpipea#pipe_reject_remote_clients

## tokio::release (function)

Releases the reserved capacity *without* sending a message, returning the
[`Sender`].

### tokio::release (function) › Examples

```
use tokio::sync::mpsc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, rx) = mpsc::channel(1);

// Clone the sender and reserve capacity
let permit = tx.clone().reserve_owned().await.unwrap();

// Trying to send on the original `tx` will fail, since the `permit`
// has reserved all the available capacity.
assert!(tx.try_send(123).is_err());

// Release the permit without sending a message, returning the clone
// of the sender.
let tx2 = permit.release();

// We may now reuse `tx` to send another message.
tx.send(789).await.unwrap();
# drop(rx); drop(tx2);
# }
```

[`Sender`]: Sender

## tokio::remaining (function)

Returns the number of bytes at the end of the slice that have not yet been filled.

## tokio::remote_schedule_count (function)

Returns the number of tasks scheduled from **outside** of the runtime.

The remote schedule count starts at zero when the runtime is created and
increases by one each time a task is woken from **outside** of the
runtime. This usually means that a task is spawned or notified from a
non-runtime thread and must be queued using the Runtime's injection
queue, which tends to be slower.

The counter is monotonically increasing. It is never decremented or
reset to zero.

### tokio::remote_schedule_count (function) › Examples

```
use tokio::runtime::Handle;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let metrics = Handle::current().metrics();

let n = metrics.remote_schedule_count();
println!("{} tasks were scheduled from outside the runtime", n);
# }
```

## tokio::remove (function)

Remove `Interest` from `self`.

Interests present in `other` but *not* in `self` are ignored.

Returns `None` if the set would be empty after removing `Interest`.

### tokio::remove (function) › Examples

```
use tokio::io::Interest;

const RW_INTEREST: Interest = Interest::READABLE.add(Interest::WRITABLE);

let w_interest = RW_INTEREST.remove(Interest::READABLE).unwrap();
assert!(!w_interest.is_readable());
assert!(w_interest.is_writable());

// Removing all interests from the set returns `None`.
assert_eq!(w_interest.remove(Interest::WRITABLE), None);

// Remove all interests at once.
assert_eq!(RW_INTEREST.remove(RW_INTEREST), None);
```

## tokio::required_bucket_count (struct_field)

The number of buckets that would have been required

## tokio::reserve (function)

Waits for channel capacity. Once capacity to send one message is
available, it is reserved for the caller.

If the channel is full, the function waits for the number of unreceived
messages to become less than the channel capacity. Capacity to send one
message is reserved for the caller. A [`Permit`] is returned to track
the reserved capacity. The [`send`] function on [`Permit`] consumes the
reserved capacity.

Dropping [`Permit`] without sending a message releases the capacity back
to the channel.

[`Permit`]: Permit
[`send`]: Permit::send

### tokio::reserve (function) › Cancel safety

This channel uses a queue to ensure that calls to `send` and `reserve`
complete in the order they were requested.  Cancelling a call to
`reserve` makes you lose your place in the queue.

### tokio::reserve (function) › Examples

```
use tokio::sync::mpsc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = mpsc::channel(1);

// Reserve capacity
let permit = tx.reserve().await.unwrap();

// Trying to send directly on the `tx` will fail due to no
// available capacity.
assert!(tx.try_send(123).is_err());

// Sending on the permit succeeds
permit.send(456);

// The value sent on the permit is received
assert_eq!(rx.recv().await.unwrap(), 456);
# }
```

## tokio::reserve_many (function)

Waits for channel capacity. Once capacity to send `n` messages is
available, it is reserved for the caller.

If the channel is full or if there are fewer than `n` permits available, the function waits
for the number of unreceived messages to become `n` less than the channel capacity.
Capacity to send `n` message is then reserved for the caller.

A [`PermitIterator`] is returned to track the reserved capacity.
You can call this [`Iterator`] until it is exhausted to
get a [`Permit`] and then call [`Permit::send`]. This function is similar to
[`try_reserve_many`] except it waits for the slots to become available.

If the channel is closed, the function returns a [`SendError`].

Dropping [`PermitIterator`] without consuming it entirely releases the remaining
permits back to the channel.

[`PermitIterator`]: PermitIterator
[`Permit`]: Permit
[`send`]: Permit::send
[`try_reserve_many`]: Sender::try_reserve_many

### tokio::reserve_many (function) › Cancel safety

This channel uses a queue to ensure that calls to `send` and `reserve_many`
complete in the order they were requested. Cancelling a call to
`reserve_many` makes you lose your place in the queue.

### tokio::reserve_many (function) › Examples

```
use tokio::sync::mpsc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = mpsc::channel(2);

// Reserve capacity
let mut permit = tx.reserve_many(2).await.unwrap();

// Trying to send directly on the `tx` will fail due to no
// available capacity.
assert!(tx.try_send(123).is_err());

// Sending with the permit iterator succeeds
permit.next().unwrap().send(456);
permit.next().unwrap().send(457);

// The iterator should now be exhausted
assert!(permit.next().is_none());

// The value sent on the permit is received
assert_eq!(rx.recv().await.unwrap(), 456);
assert_eq!(rx.recv().await.unwrap(), 457);
# }
```

## tokio::reserve_owned (function)

Waits for channel capacity, moving the `Sender` and returning an owned
permit. Once capacity to send one message is available, it is reserved
for the caller.

This moves the sender _by value_, and returns an owned permit that can
be used to send a message into the channel. Unlike [`Sender::reserve`],
this method may be used in cases where the permit must be valid for the
`'static` lifetime. `Sender`s may be cloned cheaply (`Sender::clone` is
essentially a reference count increment, comparable to [`Arc::clone`]),
so when multiple [`OwnedPermit`]s are needed or the `Sender` cannot be
moved, it can be cloned prior to calling `reserve_owned`.

If the channel is full, the function waits for the number of unreceived
messages to become less than the channel capacity. Capacity to send one
message is reserved for the caller. An [`OwnedPermit`] is returned to
track the reserved capacity. The [`send`] function on [`OwnedPermit`]
consumes the reserved capacity.

Dropping the [`OwnedPermit`] without sending a message releases the
capacity back to the channel.

### tokio::reserve_owned (function) › Cancel safety

This channel uses a queue to ensure that calls to `send` and `reserve`
complete in the order they were requested.  Cancelling a call to
`reserve_owned` makes you lose your place in the queue.

### tokio::reserve_owned (function) › Examples
Sending a message using an [`OwnedPermit`]:
```
use tokio::sync::mpsc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = mpsc::channel(1);

// Reserve capacity, moving the sender.
let permit = tx.reserve_owned().await.unwrap();

// Send a message, consuming the permit and returning
// the moved sender.
let tx = permit.send(123);

// The value sent on the permit is received.
assert_eq!(rx.recv().await.unwrap(), 123);

// The sender can now be used again.
tx.send(456).await.unwrap();
# }
```

When multiple [`OwnedPermit`]s are needed, or the sender cannot be moved
by value, it can be inexpensively cloned before calling `reserve_owned`:

```
use tokio::sync::mpsc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = mpsc::channel(1);

// Clone the sender and reserve capacity.
let permit = tx.clone().reserve_owned().await.unwrap();

// Trying to send directly on the `tx` will fail due to no
// available capacity.
assert!(tx.try_send(123).is_err());

// Sending on the permit succeeds.
permit.send(456);

// The value sent on the permit is received
assert_eq!(rx.recv().await.unwrap(), 456);
# }
```

[`Sender::reserve`]: Sender::reserve
[`OwnedPermit`]: OwnedPermit
[`send`]: OwnedPermit::send
[`Arc::clone`]: std::sync::Arc::clone

## tokio::reset (function)

Resets the `Sleep` instance to a new deadline.

Calling this function allows changing the instant at which the `Sleep`
future completes without having to create new associated state.

This function can be called both before and after the future has
completed.

To call this method, you will usually combine the call with
[`Pin::as_mut`], which lets you call the method without consuming the
`Sleep` itself.

### tokio::reset (function) › Example

```
use tokio::time::{Duration, Instant};

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let sleep = tokio::time::sleep(Duration::from_millis(10));
tokio::pin!(sleep);

sleep.as_mut().reset(Instant::now() + Duration::from_millis(20));
# }
```

See also the top-level examples.

[`Pin::as_mut`]: fn@std::pin::Pin::as_mut

## tokio::reset (function)

Resets the interval to complete one period after the current time.

This method ignores [`MissedTickBehavior`] strategy.

This is equivalent to calling `reset_at(Instant::now() + period)`.

### tokio::reset (function) › Examples

```
use tokio::time;

use std::time::Duration;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let mut interval = time::interval(Duration::from_millis(100));

interval.tick().await;

time::sleep(Duration::from_millis(50)).await;
interval.reset();

interval.tick().await;
interval.tick().await;

// approximately 250ms have elapsed.
# }
```

## tokio::reset_after (function)

Resets the interval after the specified [`std::time::Duration`].

This method ignores [`MissedTickBehavior`] strategy.

This is equivalent to calling `reset_at(Instant::now() + after)`.

### tokio::reset_after (function) › Examples

```
use tokio::time;

use std::time::Duration;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let mut interval = time::interval(Duration::from_millis(100));
interval.tick().await;

time::sleep(Duration::from_millis(50)).await;

let after = Duration::from_millis(20);
interval.reset_after(after);

interval.tick().await;
interval.tick().await;

// approximately 170ms have elapsed.
# }
```

## tokio::reset_at (function)

Resets the interval to a [`crate::time::Instant`] deadline.

Sets the next tick to expire at the given instant. If the instant is in
the past, then the [`MissedTickBehavior`] strategy will be used to
catch up. If the instant is in the future, then the next tick will
complete at the given instant, even if that means that it will sleep for
longer than the duration of this [`Interval`]. If the [`Interval`] had
any missed ticks before calling this method, then those are discarded.

### tokio::reset_at (function) › Examples

```
use tokio::time::{self, Instant};

use std::time::Duration;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let mut interval = time::interval(Duration::from_millis(100));
interval.tick().await;

time::sleep(Duration::from_millis(50)).await;

let deadline = Instant::now() + Duration::from_millis(30);
interval.reset_at(deadline);

interval.tick().await;
interval.tick().await;

// approximately 180ms have elapsed.
# }
```

## tokio::reset_immediately (function)

Resets the interval immediately.

This method ignores [`MissedTickBehavior`] strategy.

This is equivalent to calling `reset_at(Instant::now())`.

### tokio::reset_immediately (function) › Examples

```
use tokio::time;

use std::time::Duration;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let mut interval = time::interval(Duration::from_millis(100));

interval.tick().await;

time::sleep(Duration::from_millis(50)).await;
interval.reset_immediately();

interval.tick().await;
interval.tick().await;

// approximately 150ms have elapsed.
# }
```

## tokio::resolve_backtraces (function)

Resolve and return a list of backtraces that are involved in polls in this trace.

The exact backtraces included here are unstable and might change in the future,
but you can expect one [`Backtrace`] for every call to
[`poll`] to a bottom-level Tokio future - so if something like [`join!`] is
used, there will be a backtrace for each future in the join.

[`poll`]: std::future::Future::poll
[`join!`]: macro@join

## tokio::resubscribe (function)

Re-subscribes to the channel starting from the current tail element.

This [`Receiver`] handle will receive a clone of all values sent
**after** it has resubscribed. This will not include elements that are
in the queue of the current receiver. Consider the following example.

### tokio::resubscribe (function) › Examples

```
use tokio::sync::broadcast;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = broadcast::channel(2);

tx.send(1).unwrap();
let mut rx2 = rx.resubscribe();
tx.send(2).unwrap();

assert_eq!(rx2.recv().await.unwrap(), 2);
assert_eq!(rx.recv().await.unwrap(), 1);
# }
```

## tokio::retain_ready (function)

This method should be invoked when you intentionally want to keep the
ready flag asserted.

While this function is itself a no-op, it satisfies the `#[must_use]`
constraint on the [`AsyncFdReadyGuard`] type.

## tokio::retain_ready (function)

This method should be invoked when you intentionally want to keep the
ready flag asserted.

While this function is itself a no-op, it satisfies the `#[must_use]`
constraint on the [`AsyncFdReadyGuard`] type.

## tokio::reunite (function)

Attempts to put the two halves of a `TcpStream` back together and
recover the original socket. Succeeds only if the two halves
originated from the same call to [`into_split`].

[`into_split`]: TcpStream::into_split()

## tokio::reunite (function)

Attempts to put the two halves of a `TcpStream` back together and
recover the original socket. Succeeds only if the two halves
originated from the same call to [`into_split`].

[`into_split`]: TcpStream::into_split()

## tokio::reunite (function)

Attempts to put the two halves of a `UnixStream` back together and
recover the original socket. Succeeds only if the two halves
originated from the same call to [`into_split`].

[`into_split`]: crate::net::UnixStream::into_split()

## tokio::reunite (function)

Attempts to put the two halves of a `UnixStream` back together and
recover the original socket. Succeeds only if the two halves
originated from the same call to [`into_split`].

[`into_split`]: crate::net::UnixStream::into_split()

## tokio::reuseaddr (function)

Retrieves the value set for `SO_REUSEADDR` on this socket.

### tokio::reuseaddr (function) › Examples

```no_run
use tokio::net::TcpSocket;

use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let addr = "127.0.0.1:8080".parse().unwrap();

    let socket = TcpSocket::new_v4()?;
    socket.set_reuseaddr(true)?;
    assert!(socket.reuseaddr().unwrap());
    socket.bind(addr)?;

    let listener = socket.listen(1024)?;
    Ok(())
}
```

## tokio::reuseport (function)

Allows the socket to bind to an in-use port. Only available for unix systems
(excluding Solaris, Illumos, and Cygwin).

Behavior is platform specific. Refer to the target platform's
documentation for more details.

### tokio::reuseport (function) › Examples

```no_run
use tokio::net::TcpSocket;

use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let addr = "127.0.0.1:8080".parse().unwrap();

    let socket = TcpSocket::new_v4()?;
    socket.set_reuseport(true)?;
    assert!(socket.reuseport().unwrap());
    socket.bind(addr)?;

    let listener = socket.listen(1024)?;
    Ok(())
}
```

## tokio::rewind (function)

Creates a future which will rewind to the beginning of the stream.

This is convenience method, equivalent to `self.seek(SeekFrom::Start(0))`.

## tokio::rng_seed (function)

Specifies the random number generation seed to use within all
threads associated with the runtime being built.

This option is intended to make certain parts of the runtime
deterministic (e.g. the [`tokio::select!`] macro). In the case of
[`tokio::select!`] it will ensure that the order that branches are
polled is deterministic.

In addition to the code specifying `rng_seed` and interacting with
the runtime, the internals of Tokio and the Rust compiler may affect
the sequences of random numbers. In order to ensure repeatable
results, the version of Tokio, the versions of all other
dependencies that interact with Tokio, and the Rust compiler version
should also all remain constant.

### tokio::rng_seed (function) › Examples

```
# use tokio::runtime::{self, RngSeed};
# pub fn main() {
let seed = RngSeed::from_bytes(b"place your seed here");
let rt = runtime::Builder::new_current_thread()
    .rng_seed(seed)
    .build();
# }
```

[`tokio::select!`]: crate::select

## tokio::root (function)

Create a root for stack traces captured using [`Trace::capture`]. Stack frames above
the root will not be captured.

Nesting multiple [`Root`] futures is fine. Captures will stop at the first root. Not having
a [`Root`] is fine as well, but there is no guarantee on where the capture will stop.

## tokio::root_addr (struct_field)

The root boundary address set by [`Root::poll`] if any.

When using unwinding the stack, this is the address at which
stack walking should stop. It corresponds to the `Root::poll` function pointer.

## tokio::run_until (function)

Runs a future to completion on the local set, returning its output.

This returns a future that runs the given future with a local set,
allowing it to call [`spawn_local`] to spawn additional `!Send` futures.
Any local futures spawned on the local set will be driven in the
background until the future passed to `run_until` completes. When the future
passed to `run_until` finishes, any local futures which have not completed
will remain on the local set, and will be driven on subsequent calls to
`run_until` or when [awaiting the local set] itself.

### tokio::run_until (function) › Cancel safety

This method is cancel safe when `future` is cancel safe.

### tokio::run_until (function) › Examples

```rust
use tokio::task;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
task::LocalSet::new().run_until(async {
    task::spawn_local(async move {
        // ...
    }).await.unwrap();
    // ...
}).await;
# }
```

[`spawn_local`]: fn@spawn_local
[awaiting the local set]: #awaiting-a-localset

## tokio::runtime::builder::Builder (struct)

Builds Tokio Runtime with custom configuration values.

Methods can be chained in order to set the configuration values. The
Runtime is constructed by calling [`build`].

New instances of `Builder` are obtained via [`Builder::new_multi_thread`]
or [`Builder::new_current_thread`].

See function level documentation for details on the various configuration
settings.

[`build`]: method@Self::build
[`Builder::new_multi_thread`]: method@Self::new_multi_thread
[`Builder::new_current_thread`]: method@Self::new_current_thread

### tokio::runtime::builder::Builder (struct) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime::Builder;

fn main() {
    // build runtime
    let runtime = Builder::new_multi_thread()
        .worker_threads(4)
        .thread_name("my-custom-name")
        .thread_stack_size(3 * 1024 * 1024)
        .build()
        .unwrap();

    // use runtime ...
}
# }
```

## tokio::runtime::builder::UnhandledPanic (enum)

How the runtime should respond to unhandled panics.

Instances of `UnhandledPanic` are passed to `Builder::unhandled_panic`
to configure the runtime behavior when a spawned task panics.

See [`Builder::unhandled_panic`] for more details.

## tokio::runtime::builder::UnhandledPanic::Ignore (variant)

The runtime should ignore panics on spawned tasks.

The panic is forwarded to the task's [`JoinHandle`] and all spawned
tasks continue running normally.

This is the default behavior.

### tokio::runtime::builder::UnhandledPanic::Ignore (variant) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime::{self, UnhandledPanic};

# pub fn main() {
let rt = runtime::Builder::new_current_thread()
    .unhandled_panic(UnhandledPanic::Ignore)
    .build()
    .unwrap();

let task1 = rt.spawn(async { panic!("boom"); });
let task2 = rt.spawn(async {
    // This task completes normally
    "done"
});

rt.block_on(async {
    // The panic on the first task is forwarded to the `JoinHandle`
    assert!(task1.await.is_err());

    // The second task completes normally
    assert!(task2.await.is_ok());
})
# }
# }
```

[`JoinHandle`]: struct@crate::task::JoinHandle

## tokio::runtime::builder::UnhandledPanic::ShutdownRuntime (variant)

The runtime should immediately shutdown if a spawned task panics.

The runtime will immediately shutdown even if the panicked task's
[`JoinHandle`] is still available. All further spawned tasks will be
immediately dropped and call to [`Runtime::block_on`] will panic.

### tokio::runtime::builder::UnhandledPanic::ShutdownRuntime (variant) › Examples

```should_panic
use tokio::runtime::{self, UnhandledPanic};

# pub fn main() {
let rt = runtime::Builder::new_current_thread()
    .unhandled_panic(UnhandledPanic::ShutdownRuntime)
    .build()
    .unwrap();

rt.spawn(async { panic!("boom"); });
rt.spawn(async {
    // This task never completes.
});

rt.block_on(async {
    // Do some work
# loop { tokio::task::yield_now().await; }
})
# }
```

[`JoinHandle`]: struct@crate::task::JoinHandle

## tokio::runtime::dump::Backtrace (struct)

A captured backtrace.

This struct provides access to each backtrace frame, similar to [`backtrace::Backtrace`].

## tokio::runtime::dump::BacktraceFrame (struct)

A backtrace frame.

This struct represents one stack frame in a captured backtrace, similar to [`backtrace::BacktraceFrame`].

## tokio::runtime::dump::BacktraceSymbol (struct)

A backtrace symbol.

This struct provides accessors for backtrace symbols, similar to [`backtrace::BacktraceSymbol`].

## tokio::runtime::dump::Dump (struct)

A snapshot of a runtime's state.

See [`Handle::dump`][crate::runtime::Handle::dump].

## tokio::runtime::dump::Task (struct)

A snapshot of a task.

See [`Handle::dump`][crate::runtime::Handle::dump].

## tokio::runtime::dump::Tasks (struct)

Snapshots of tasks.

See [`Handle::dump`][crate::runtime::Handle::dump].

## tokio::runtime::dump::Trace (struct)

An execution trace of a task's last poll.

<div class="warning">

Resolving a backtrace, either via the [`Display`][std::fmt::Display] impl or via
[`resolve_backtraces`][Trace::resolve_backtraces], parses debuginfo, which is
possibly a CPU-expensive operation that can take a platform-specific but
long time to run - often over 100 milliseconds, especially if the current
process's binary is big. In some cases, the platform might internally cache some of the
debuginfo, so successive calls to `resolve_backtraces` might be faster than
the first call, but all guarantees are platform-dependent.

To avoid blocking the runtime, it is recommended
that you resolve backtraces inside of a [`spawn_blocking()`][crate::task::spawn_blocking]
and to have some concurrency-limiting mechanism to avoid unexpected performance impact.
</div>

See [`Handle::dump`][crate::runtime::Handle::dump].

## tokio::runtime::handle::EnterGuard (struct)

Runtime context guard.

Returned by [`Runtime::enter`] and [`Handle::enter`], the context guard exits
the runtime context on drop.

[`Runtime::enter`]: fn@crate::runtime::Runtime::enter

## tokio::runtime::handle::Handle (struct)

Handle to the runtime.

The handle is internally reference-counted and can be freely cloned. A handle can be
obtained using the [`Runtime::handle`] method.

[`Runtime::handle`]: crate::runtime::Runtime::handle()

## tokio::runtime::handle::TryCurrentError (struct)

Error returned by `try_current` when no Runtime has been started

## tokio::runtime::id::Id (struct)

An opaque ID that uniquely identifies a runtime relative to all other currently
running runtimes.

### tokio::runtime::id::Id (struct) › Notes

- Runtime IDs are unique relative to other *currently running* runtimes.
  When a runtime completes, the same ID may be used for another runtime.
- Runtime IDs are *not* sequential, and do not indicate the order in which
  runtimes are started or any other data.
- The runtime ID of the currently running task can be obtained from the
  Handle.

### tokio::runtime::id::Id (struct) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime::Handle;

#[tokio::main(flavor = "multi_thread", worker_threads = 4)]
async fn main() {
  println!("Current runtime id: {}", Handle::current().id());
}
# }
```

## tokio::runtime::local_runtime::options::LocalOptions (struct)

[`LocalRuntime`]-only config options

Currently, there are no such options, but in the future, things like `!Send + !Sync` hooks may
be added.

Use `LocalOptions::default()` to create the default set of options. This type is used with
[`Builder::build_local`].

[`Builder::build_local`]: crate::runtime::Builder::build_local
[`LocalRuntime`]: crate::runtime::LocalRuntime

## tokio::runtime::local_runtime::runtime::LocalRuntime (struct)

A local Tokio runtime.

This runtime is capable of driving tasks which are not `Send + Sync` without the use of a
`LocalSet`, and thus supports `spawn_local` without the need for a `LocalSet` context.

This runtime cannot be moved between threads or driven from different threads.

This runtime is incompatible with `LocalSet`. You should not attempt to drive a `LocalSet` within a
`LocalRuntime`.

Currently, this runtime supports one flavor, which is internally identical to `current_thread`,
save for the aforementioned differences related to `spawn_local`.

For more general information on how to use runtimes, see the [module] docs.

[runtime]: crate::runtime::Runtime
[module]: crate::runtime

## tokio::runtime::metrics::histogram::HistogramConfiguration (struct)

Configuration for the poll count histogram

## tokio::runtime::metrics::histogram::HistogramScale (enum)

Whether the histogram used to aggregate a metric uses a linear or
logarithmic scale.

## tokio::runtime::metrics::histogram::HistogramScale::Linear (variant)

Linear bucket scale

## tokio::runtime::metrics::histogram::HistogramScale::Log (variant)

Logarithmic bucket scale

## tokio::runtime::metrics::histogram::h2_histogram::InvalidHistogramConfiguration (enum)

Error constructing a histogram

## tokio::runtime::metrics::histogram::h2_histogram::InvalidHistogramConfiguration::TooManyBuckets (variant)

This histogram required more than the specified number of buckets

## tokio::runtime::metrics::histogram::h2_histogram::LogHistogram (struct)

Log Histogram

This implements an [H2 Histogram](https://iop.systems/blog/h2-histogram/), a histogram similar
to HdrHistogram, but with better performance. It guarantees an error bound of `2^-p`.

Unlike a traditional H2 histogram this has two small changes:
1. The 0th bucket runs for `0..min_value`. This allows truncating a large number of buckets that
   would cover extremely short timescales that customers usually don't care about.
2. The final bucket runs all the way to `u64::MAX` — traditional H2 histograms would truncate
   or reject these values.

For information about the default configuration, see [`LogHistogramBuilder`].

## tokio::runtime::metrics::histogram::h2_histogram::LogHistogramBuilder (struct)

Configuration for a [`LogHistogram`]

The log-scaled histogram implements an H2 histogram where the first bucket covers
the range from 0 to [`LogHistogramBuilder::min_value`] and the final bucket covers
[`LogHistogramBuilder::max_value`] to infinity. The precision is bounded to the specified
[`LogHistogramBuilder::max_error`]. Specifically, the precision is the next smallest value
of `2^-p` such that it is smaller than the requested max error. You can also select `p` directly
with [`LogHistogramBuilder::precision_exact`].

Depending on the selected parameters, the number of buckets required is variable. To ensure
that the histogram size is acceptable, callers may call [`LogHistogramBuilder::max_buckets`].
If the resulting histogram would require more buckets, then the method will return an error.

### tokio::runtime::metrics::histogram::h2_histogram::LogHistogramBuilder (struct) › Default values
The default configuration provides the following settings:
1. `min_value`: 100ns
2. `max_value`: 68 seconds. The final bucket covers all values >68 seconds
3. `precision`: max error of 25%

This uses 237 64-bit buckets.

## tokio::runtime::metrics::runtime::RuntimeMetrics (struct)

Handle to the runtime's metrics.

This handle is internally reference-counted and can be freely cloned. A
`RuntimeMetrics` handle is obtained using the [`Runtime::metrics`] method.

[`Runtime::metrics`]: crate::runtime::Runtime::metrics()

## tokio::runtime::runtime::Runtime (struct)

The Tokio runtime.

The runtime provides an I/O driver, task scheduler, [timer], and
blocking pool, necessary for running asynchronous tasks.

Instances of `Runtime` can be created using [`new`], or [`Builder`].
However, most users will use the [`#[tokio::main]`][main] annotation on
their entry point instead.

See [module level][mod] documentation for more details.

### tokio::runtime::runtime::Runtime (struct) › Shutdown

Shutting down the runtime is done by dropping the value, or calling
[`shutdown_background`] or [`shutdown_timeout`].

Tasks spawned through [`Runtime::spawn`] keep running until they yield.
Then they are dropped. They are not *guaranteed* to run to completion, but
*might* do so if they do not yield until completion.

Blocking functions spawned through [`Runtime::spawn_blocking`] keep running
until they return.

The thread initiating the shutdown blocks until all spawned work has been
stopped. This can take an indefinite amount of time. The `Drop`
implementation waits forever for this.

The [`shutdown_background`] and [`shutdown_timeout`] methods can be used if
waiting forever is undesired. When the timeout is reached, spawned work that
did not stop in time and threads running it are leaked. The work continues
to run until one of the stopping conditions is fulfilled, but the thread
initiating the shutdown is unblocked.

Once the runtime has been dropped, any outstanding I/O resources bound to
it will no longer function. Calling any method on them will result in an
error.

### tokio::runtime::runtime::Runtime (struct) › Sharing

There are several ways to establish shared access to a Tokio runtime:

 * Using an <code>[Arc]\<Runtime></code>.
 * Using a [`Handle`].
 * Entering the runtime context.

Using an <code>[Arc]\<Runtime></code> or [`Handle`] allows you to do various
things with the runtime such as spawning new tasks or entering the runtime
context. Both types can be cloned to create a new handle that allows access
to the same runtime. By passing clones into different tasks or threads, you
will be able to access the runtime from those tasks or threads.

The difference between <code>[Arc]\<Runtime></code> and [`Handle`] is that
an <code>[Arc]\<Runtime></code> will prevent the runtime from shutting down,
whereas a [`Handle`] does not prevent that. This is because shutdown of the
runtime happens when the destructor of the `Runtime` object runs.

Calls to [`shutdown_background`] and [`shutdown_timeout`] require exclusive
ownership of the `Runtime` type. When using an <code>[Arc]\<Runtime></code>,
this can be achieved via [`Arc::try_unwrap`] when only one strong count
reference is left over.

The runtime context is entered using the [`Runtime::enter`] or
[`Handle::enter`] methods, which use a thread-local variable to store the
current runtime. Whenever you are inside the runtime context, methods such
as [`tokio::spawn`] will use the runtime whose context you are inside.

[timer]: crate::time
[mod]: index.html
[`new`]: method@Self::new
[`Builder`]: struct@Builder
[`Handle`]: struct@Handle
[main]: macro@crate::main
[`tokio::spawn`]: crate::spawn
[`Arc::try_unwrap`]: std::sync::Arc::try_unwrap
[Arc]: std::sync::Arc
[`shutdown_background`]: method@Runtime::shutdown_background
[`shutdown_timeout`]: method@Runtime::shutdown_timeout

## tokio::runtime::runtime::RuntimeFlavor (enum)

The flavor of a `Runtime`.

This is the return type for [`Handle::runtime_flavor`](crate::runtime::Handle::runtime_flavor()).

## tokio::runtime::runtime::RuntimeFlavor::CurrentThread (variant)

The flavor that executes all tasks on the current thread.

## tokio::runtime::runtime::RuntimeFlavor::MultiThread (variant)

The flavor that executes tasks across multiple threads.

## tokio::runtime::runtime::is_rt_shutdown_err (function)

Checks whether the given error was emitted by Tokio when shutting down its runtime.

### tokio::runtime::runtime::is_rt_shutdown_err (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime::Runtime;
use tokio::net::TcpListener;

fn main() {
    let rt1 = Runtime::new().unwrap();
    let rt2 = Runtime::new().unwrap();

    let listener = rt1.block_on(async {
        TcpListener::bind("127.0.0.1:0").await.unwrap()
    });

    drop(rt1);

    rt2.block_on(async {
        let res = listener.accept().await;
        assert!(res.is_err());
        assert!(tokio::runtime::is_rt_shutdown_err(res.as_ref().unwrap_err()));
    });
}
# }
```

## tokio::runtime::task::abort::AbortHandle (struct)

An owned permission to abort a spawned task, without awaiting its completion.

Unlike a [`JoinHandle`], an `AbortHandle` does *not* represent the
permission to await the task's completion, only to terminate it.

The task may be aborted by calling the [`AbortHandle::abort`] method.
Dropping an `AbortHandle` releases the permission to terminate the task
--- it does *not* abort the task.

Be aware that tasks spawned using [`spawn_blocking`] cannot be aborted
because they are not async. If you call `abort` on a `spawn_blocking` task,
then this *will not have any effect*, and the task will continue running
normally. The exception is if the task has not started running yet; in that
case, calling `abort` may prevent the task from starting.

[`JoinHandle`]: crate::task::JoinHandle
[`spawn_blocking`]: crate::task::spawn_blocking

## tokio::runtime::task::error::JoinError (struct)

Task failed to execute to completion.

## tokio::runtime::task::id::Id (struct)

An opaque ID that uniquely identifies a task relative to all other currently
running tasks.

A task's ID may be re-used for another task only once *both* of the
following happen:
1. The task itself exits.
2. There is no active [`JoinHandle`] associated with this task.

A [`JoinHandle`] is considered active in the following situations:
- You are explicitly holding a [`JoinHandle`], [`AbortHandle`], or
  `tokio_util::task::AbortOnDropHandle`.
- The task is being tracked by a [`JoinSet`] or `tokio_util::task::JoinMap`.

### tokio::runtime::task::id::Id (struct) › Notes

- Task IDs are *not* sequential, and do not indicate the order in which
  tasks are spawned, what runtime a task is spawned on, or any other data.
- The task ID of the currently running task can be obtained from inside the
  task via the [`task::try_id()`](crate::task::try_id()) and
  [`task::id()`](crate::task::id()) functions and from outside the task via
  the [`JoinHandle::id()`](crate::task::JoinHandle::id()) function.

[`JoinHandle`]: crate::task::JoinHandle
[`AbortHandle`]: crate::task::AbortHandle
[`JoinSet`]: crate::task::JoinSet

## tokio::runtime::task::id::id (function)

Returns the [`Id`] of the currently running task.

### tokio::runtime::task::id::id (function) › Panics

This function panics if called from outside a task. Please note that calls
to `block_on` do not have task IDs, so the method will panic if called from
within a call to `block_on`. For a version of this function that doesn't
panic, see [`task::try_id()`](crate::runtime::task::try_id()).

[task ID]: crate::task::Id

## tokio::runtime::task::id::try_id (function)

Returns the [`Id`] of the currently running task, or `None` if called outside
of a task.

This function is similar to  [`task::id()`](crate::runtime::task::id()), except
that it returns `None` rather than panicking if called outside of a task
context.

[task ID]: crate::task::Id

## tokio::runtime::task::join::JoinHandle (struct)

An owned permission to join on a task (await its termination).

This can be thought of as the equivalent of [`std::thread::JoinHandle`]
for a Tokio task rather than a thread. Note that the background task
associated with this `JoinHandle` started running immediately when you
called spawn, even if you have not yet awaited the `JoinHandle`.

A `JoinHandle` *detaches* the associated task when it is dropped, which
means that there is no longer any handle to the task, and no way to `join`
on it.

This `struct` is created by the [`task::spawn`] and [`task::spawn_blocking`]
functions.

It is guaranteed that the destructor of the spawned task has finished
before task completion is observed via `JoinHandle` `await`,
[`JoinHandle::is_finished`] or [`AbortHandle::is_finished`].

### tokio::runtime::task::join::JoinHandle (struct) › Cancel safety

Awaiting a `&mut JoinHandle<T>` is cancel safe. If it is used as a
branch in `tokio::select!` and another branch completes first, then it
is guaranteed that the output of the task is not lost.

If a `JoinHandle` is dropped, then the task continues running in the
background and its return value is lost.

### tokio::runtime::task::join::JoinHandle (struct) › Examples

Creation from [`task::spawn`]:

```
use tokio::task;

# async fn doc() {
let join_handle: task::JoinHandle<_> = task::spawn(async {
    // some work here
});
# }
```

Creation from [`task::spawn_blocking`]:

```
use tokio::task;

# async fn doc() {
let join_handle: task::JoinHandle<_> = task::spawn_blocking(|| {
    // some blocking work here
});
# }
```

The generic parameter `T` in `JoinHandle<T>` is the return type of the spawned task.
If the return value is an `i32`, the join handle has type `JoinHandle<i32>`:

```
use tokio::task;

# async fn doc() {
let join_handle: task::JoinHandle<i32> = task::spawn(async {
    5 + 3
});
# }

```

If the task does not have a return value, the join handle has type `JoinHandle<()>`:

```
use tokio::task;

# async fn doc() {
let join_handle: task::JoinHandle<()> = task::spawn(async {
    println!("I return nothing.");
});
# }
```

Note that `handle.await` doesn't give you the return type directly. It is wrapped in a
`Result` because panics in the spawned task are caught by Tokio. The `?` operator has
to be double chained to extract the returned value:

```
use tokio::task;
use std::io;

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let join_handle: task::JoinHandle<Result<i32, io::Error>> = tokio::spawn(async {
    Ok(5 + 3)
});

let result = join_handle.await??;
assert_eq!(result, 8);
Ok(())
# }
```

If the task panics, the error is a [`JoinError`] that contains the panic:

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::task;
use std::io;
use std::panic;

#[tokio::main]
async fn main() -> io::Result<()> {
    let join_handle: task::JoinHandle<Result<i32, io::Error>> = tokio::spawn(async {
        panic!("boom");
    });

    let err = join_handle.await.unwrap_err();
    assert!(err.is_panic());
    Ok(())
}
# }
```
Child being detached and outliving its parent:

```no_run
use tokio::task;
use tokio::time;
use std::time::Duration;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let original_task = task::spawn(async {
    let _detached_task = task::spawn(async {
        // Here we sleep to make sure that the first task returns before.
        time::sleep(Duration::from_millis(10)).await;
        // This will be called, even though the JoinHandle is dropped.
        println!("♫ Still alive ♫");
    });
});

original_task.await.expect("The task being joined has panicked");
println!("Original task is joined.");

// We make sure that the new task has time to run, before the main
// task returns.

time::sleep(Duration::from_millis(1000)).await;
# }
```

[`task::spawn`]: crate::task::spawn()
[`task::spawn_blocking`]: crate::task::spawn_blocking
[`std::thread::JoinHandle`]: std::thread::JoinHandle
[`JoinError`]: crate::task::JoinError

## tokio::runtime::task::trace::Root (struct)

A future wrapper that roots traces (captured with [`Trace::capture`]).

## tokio::runtime::task::trace::TraceMeta (struct)

Metadata passed into the `trace_leaf` callback for [`trace_with`]

## tokio::runtime::task::trace::trace_with (function)

Runs `f`. If `f` hits a Tokio yield point `trace_leaf` will be invoked.

This allows taking a task dump with caller-provided task dump machinery. If `f` is the poll
function of a future and that future returns `Poll::Pending`, then `trace_leaf` will be
invoked. `trace_leaf` can then take a backtrace to determine exactly where the yield occurred.

### tokio::runtime::task::trace::trace_with (function) › Example

```
use std::future::Future;
use std::task::Poll;
use tokio::runtime::dump::{trace_with, Trace, TraceMeta};

fn my_trace_leaf(_meta: &TraceMeta, count: &mut u32) {
    *count += 1;
}

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let mut fut = std::pin::pin!(async {
    tokio::task::yield_now().await;
});

let mut leaf_count = 0;

Trace::root(std::future::poll_fn(|cx| {
    trace_with(
        || { let _ = fut.as_mut().poll(cx); },
        |meta| my_trace_leaf(meta, &mut leaf_count),
    );
    Poll::Ready(())
})).await;

assert!(leaf_count > 0);
# }
```

## tokio::runtime::task_hooks::TaskMeta (struct)

Task metadata supplied to user-provided hooks for task events.

**Note**: This is an [unstable API][unstable]. The public API of this type
may break in 1.x releases. See [the documentation on unstable
features][unstable] for details.

[unstable]: crate#unstable-features

## tokio::runtime::worker_index (function)

Returns the index of the current worker thread, if called from a
runtime worker thread.

The returned value is a 0-based index matching the worker indices
used by [`RuntimeMetrics`] methods such as
[`worker_total_busy_duration`](RuntimeMetrics::worker_total_busy_duration).

Returns `None` when called from outside a runtime worker thread
(for example, from a blocking thread or a non-Tokio thread). On the
multi-thread runtime, the thread that calls [`Runtime::block_on`] is
not a worker thread, so this also returns `None` there.

For the current-thread runtime and [`LocalRuntime`], this always
returns `Some(0)` (including inside `block_on`, since the calling
thread *is* the worker thread).

Note that the result may change across `.await` points, as the
task may be moved to a different worker thread by the scheduler.

### tokio::runtime::worker_index (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
#[tokio::main(flavor = "multi_thread", worker_threads = 4)]
async fn main() {
    let index = tokio::spawn(async {
        tokio::runtime::worker_index()
    }).await.unwrap();
    println!("Task ran on worker {:?}", index);
}
# }
```

## tokio::runtime_flavor (function)

Returns the flavor of the current `Runtime`.

### tokio::runtime_flavor (function) › Examples

```
use tokio::runtime::{Handle, RuntimeFlavor};

#[tokio::main(flavor = "current_thread")]
async fn main() {
  assert_eq!(RuntimeFlavor::CurrentThread, Handle::current().runtime_flavor());
}
```

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime::{Handle, RuntimeFlavor};

#[tokio::main(flavor = "multi_thread", worker_threads = 4)]
async fn main() {
  assert_eq!(RuntimeFlavor::MultiThread, Handle::current().runtime_flavor());
}
# }
```

## tokio::rwlock (function)

Returns a reference to the original `Arc<RwLock>`.

### tokio::rwlock (function) › Examples

```
use std::sync::Arc;
use tokio::sync::{
    RwLock,
    OwnedRwLockWriteGuard,
    OwnedRwLockMappedWriteGuard,
};

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let lock = Arc::new(RwLock::new(1));

let guard = lock.clone().write_owned().await;
let guard = OwnedRwLockWriteGuard::map(guard, |x| x);
assert!(Arc::ptr_eq(&lock, OwnedRwLockMappedWriteGuard::rwlock(&guard)));
# }
```

## tokio::rwlock (function)

Returns a reference to the original `Arc<RwLock>`.

### tokio::rwlock (function) › Examples

```
use std::sync::Arc;
use tokio::sync::{RwLock, OwnedRwLockReadGuard};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Foo(u32);

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let lock = Arc::new(RwLock::new(Foo(1)));

let guard = lock.clone().read_owned().await;
assert!(Arc::ptr_eq(&lock, OwnedRwLockReadGuard::rwlock(&guard)));

let guard = OwnedRwLockReadGuard::map(guard, |f| &f.0);
assert!(Arc::ptr_eq(&lock, OwnedRwLockReadGuard::rwlock(&guard)));
# }
```

## tokio::rwlock (function)

Returns a reference to the original `Arc<RwLock>`.

### tokio::rwlock (function) › Examples

```
use std::sync::Arc;
use tokio::sync::{RwLock, OwnedRwLockWriteGuard};

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let lock = Arc::new(RwLock::new(1));

let guard = lock.clone().write_owned().await;
assert!(Arc::ptr_eq(&lock, OwnedRwLockWriteGuard::rwlock(&guard)));
# }
```

## tokio::same_channel (function)

Returns `true` if permits belong to the same channel.

### tokio::same_channel (function) › Examples

```
use tokio::sync::mpsc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, rx) = mpsc::channel::<()>(2);

let permit1 = tx.clone().reserve_owned().await.unwrap();
let permit2 = tx.clone().reserve_owned().await.unwrap();
assert!(permit1.same_channel(&permit2));

let (tx2, rx2) = mpsc::channel::<()>(1);

let permit3 = tx2.clone().reserve_owned().await.unwrap();
assert!(!permit3.same_channel(&permit2));
# }
```

## tokio::same_channel (function)

Returns `true` if receivers belong to the same channel.

### tokio::same_channel (function) › Examples

```
let (tx, rx) = tokio::sync::watch::channel(true);
let rx2 = rx.clone();
assert!(rx.same_channel(&rx2));

let (tx3, rx3) = tokio::sync::watch::channel(true);
assert!(!rx3.same_channel(&rx2));
```

## tokio::same_channel (function)

Returns `true` if receivers belong to the same channel.

### tokio::same_channel (function) › Examples

```
use tokio::sync::broadcast;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, rx) = broadcast::channel::<()>(16);
let rx2 = tx.subscribe();

assert!(rx.same_channel(&rx2));

let (_tx3, rx3) = broadcast::channel::<()>(16);

assert!(!rx3.same_channel(&rx2));
# }
```

## tokio::same_channel (function)

Returns `true` if senders belong to the same channel.

### tokio::same_channel (function) › Examples

```
let (tx, rx) = tokio::sync::mpsc::channel::<()>(1);
let  tx2 = tx.clone();
assert!(tx.same_channel(&tx2));

let (tx3, rx3) = tokio::sync::mpsc::channel::<()>(1);
assert!(!tx3.same_channel(&tx2));
```

## tokio::same_channel (function)

Returns `true` if senders belong to the same channel.

### tokio::same_channel (function) › Examples

```
let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<()>();
let  tx2 = tx.clone();
assert!(tx.same_channel(&tx2));

let (tx3, rx3) = tokio::sync::mpsc::unbounded_channel::<()>();
assert!(!tx3.same_channel(&tx2));
```

## tokio::same_channel (function)

Returns `true` if senders belong to the same channel.

### tokio::same_channel (function) › Examples

```
let (tx, rx) = tokio::sync::watch::channel(true);
let tx2 = tx.clone();
assert!(tx.same_channel(&tx2));

let (tx3, rx3) = tokio::sync::watch::channel(true);
assert!(!tx3.same_channel(&tx2));
```

## tokio::same_channel (function)

Returns `true` if senders belong to the same channel.

### tokio::same_channel (function) › Examples

```
use tokio::sync::broadcast;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, _rx) = broadcast::channel::<()>(16);
let tx2 = tx.clone();

assert!(tx.same_channel(&tx2));

let (tx3, _rx3) = broadcast::channel::<()>(16);

assert!(!tx3.same_channel(&tx2));
# }
```

## tokio::same_channel_as_sender (function)

Returns `true` if this permit belongs to the same channel as the given [`Sender`].

### tokio::same_channel_as_sender (function) › Examples

```
use tokio::sync::mpsc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, rx) = mpsc::channel::<()>(1);

let permit = tx.clone().reserve_owned().await.unwrap();
assert!(permit.same_channel_as_sender(&tx));

let (tx2, rx2) = mpsc::channel::<()>(1);
assert!(!permit.same_channel_as_sender(&tx2));
# }
```

## tokio::saturating_duration_since (function)

Returns the amount of time elapsed from another instant to this one, or
zero duration if that instant is later than this one.

### tokio::saturating_duration_since (function) › Examples

```
use tokio::time::{Duration, Instant, sleep};

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let now = Instant::now();
sleep(Duration::new(1, 0)).await;
let new_now = Instant::now();
println!("{:?}", new_now.saturating_duration_since(now));
println!("{:?}", now.saturating_duration_since(new_now)); // 0ns
}
```

## tokio::schedule_latency_histogram_bucket_count (function)

Returns the number of times the given worker polled tasks with a schedule
latency within the given bucket's range.

Each worker maintains its own histogram and the counts for each bucket
starts at zero when the runtime is created. Each time the worker polls a
task, it tracks the time elapsed between when the task was scheduled and
when it was polled and increments the associated bucket by 1.

Each bucket is a monotonically increasing counter. It is never
decremented or reset to zero.

### tokio::schedule_latency_histogram_bucket_count (function) › Arguments

`worker` is the index of the worker being queried. The given value must
be between 0 and `num_workers()`. The index uniquely identifies a single
worker and will continue to identify the worker throughout the lifetime
of the runtime instance.

`bucket` is the index of the bucket being queried. The bucket is scoped
to the worker. The range represented by the bucket can be queried by
calling [`schedule_latency_histogram_bucket_range()`]. Each worker maintains
identical bucket ranges.

### tokio::schedule_latency_histogram_bucket_count (function) › Panics

The method panics when `worker` represents an invalid worker, i.e. is
greater than or equal to `num_workers()` or if `bucket` represents an
invalid bucket.

### tokio::schedule_latency_histogram_bucket_count (function) › Examples

```
use tokio::runtime::{self, Handle};

fn main() {
    runtime::Builder::new_current_thread()
        .enable_metrics_schedule_latency_histogram()
        .build()
        .unwrap()
        .block_on(async {
            let metrics = Handle::current().metrics();
            let buckets = metrics.schedule_latency_histogram_num_buckets();

            for worker in 0..metrics.num_workers() {
                for i in 0..buckets {
                    let range = metrics.schedule_latency_histogram_bucket_range(i);
                    let count = metrics.schedule_latency_histogram_bucket_count(worker, i);
                    println!("{} tasks encountered a scheduling latency between {}us and {}us", count, range.start.as_micros(), range.end.as_micros());
                }
            }
        });
}
```

[`schedule_latency_histogram_bucket_range()`]: crate::runtime::RuntimeMetrics::schedule_latency_histogram_bucket_range

## tokio::schedule_latency_histogram_bucket_range (function)

Returns the range of task schedule latencies tracked by the given bucket.

This value is configured by calling
[`metrics_schedule_latency_histogram_configuration()`] when building the runtime.

### tokio::schedule_latency_histogram_bucket_range (function) › Panics

The method panics if `bucket` represents an invalid bucket index, i.e.
is greater than or equal to `schedule_latency_histogram_num_buckets()`.

### tokio::schedule_latency_histogram_bucket_range (function) › Examples

```
use tokio::runtime::{self, Handle};

fn main() {
    runtime::Builder::new_current_thread()
        .enable_metrics_schedule_latency_histogram()
        .build()
        .unwrap()
        .block_on(async {
            let metrics = Handle::current().metrics();
            let buckets = metrics.schedule_latency_histogram_num_buckets();

            for i in 0..buckets {
                let range = metrics.schedule_latency_histogram_bucket_range(i);
                println!("Histogram bucket {} range: {:?}", i, range);
            }
        });
}
```

[`metrics_schedule_latency_histogram_configuration()`]: crate::runtime::Builder::metrics_schedule_latency_histogram_configuration

## tokio::schedule_latency_histogram_enabled (function)

Returns `true` if the runtime is tracking the distribution of task
schedule latencies.

Task schedule latencies are not instrumented by default as doing so
requires calling [`Instant::now()`] when a task is scheduled and when
it is polled. The feature is enabled by calling
[`enable_metrics_schedule_latency_histogram()`] when building the runtime.

### tokio::schedule_latency_histogram_enabled (function) › Examples

```
use tokio::runtime::{self, Handle};

fn main() {
    runtime::Builder::new_current_thread()
        .enable_metrics_schedule_latency_histogram()
        .build()
        .unwrap()
        .block_on(async {
            let metrics = Handle::current().metrics();
            let enabled = metrics.schedule_latency_histogram_enabled();

            println!("Tracking task schedule latency distribution: {:?}", enabled);
        });
}
```

[`enable_metrics_schedule_latency_histogram()`]: crate::runtime::Builder::enable_metrics_schedule_latency_histogram
[`Instant::now()`]: std::time::Instant::now

## tokio::schedule_latency_histogram_num_buckets (function)

Returns the number of histogram buckets tracking the distribution of
task schedule latencies.

This value is configured by calling
[`metrics_schedule_latency_histogram_configuration()`] when building the runtime.

### tokio::schedule_latency_histogram_num_buckets (function) › Examples

```
use tokio::runtime::{self, Handle};

fn main() {
    runtime::Builder::new_current_thread()
        .enable_metrics_schedule_latency_histogram()
        .build()
        .unwrap()
        .block_on(async {
            let metrics = Handle::current().metrics();
            let buckets = metrics.schedule_latency_histogram_num_buckets();

            println!("Histogram buckets: {:?}", buckets);
        });
}
```

[`metrics_schedule_latency_histogram_configuration()`]: crate::runtime::Builder::metrics_schedule_latency_histogram_configuration

## tokio::scope (function)

Sets a value `T` as the task-local value for the future `F`.

On completion of `scope`, the task-local will be dropped.

### tokio::scope (function) › Panics

If you poll the returned future inside a call to [`with`] or
[`try_with`] on the same `LocalKey`, then the call to `poll` will panic.

### tokio::scope (function) › Examples

```
# async fn dox() {
tokio::task_local! {
    static NUMBER: u32;
}

NUMBER.scope(1, async move {
    println!("task local value: {}", NUMBER.get());
}).await;
# }
```

[`with`]: fn@Self::with
[`try_with`]: fn@Self::try_with

## tokio::security_qos_flags (function)

Sets qos flags which are combined with other flags and attributes in the
call to [`CreateFile`].

By default `security_qos_flags` is set to [`SECURITY_IDENTIFICATION`],
calling this function would override that value completely with the
argument specified.

When `security_qos_flags` is not set, a malicious program can gain the
elevated privileges of a privileged Rust process when it allows opening
user-specified paths, by tricking it into opening a named pipe. So
arguably `security_qos_flags` should also be set when opening arbitrary
paths. However the bits can then conflict with other flags, specifically
`FILE_FLAG_OPEN_NO_RECALL`.

For information about possible values, see [Impersonation Levels] on the
Windows Dev Center site. The `SECURITY_SQOS_PRESENT` flag is set
automatically when using this method.

[`CreateFile`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea
[`SECURITY_IDENTIFICATION`]: https://docs.rs/windows-sys/latest/windows_sys/Win32/Storage/FileSystem/constant.SECURITY_IDENTIFICATION.html
[Impersonation Levels]: https://docs.microsoft.com/en-us/windows/win32/api/winnt/ne-winnt-security_impersonation_level

## tokio::security_qos_flags (function)

Sets the `dwSecurityQosFlags` argument to the call to [`CreateFile2`] to
the specified value (or combines it with `custom_flags` and `attributes`
to set the `dwFlagsAndAttributes` for [`CreateFile`]).

By default `security_qos_flags` is not set. It should be specified when
opening a named pipe, to control to which degree a server process can
act on behalf of a client process (security impersonation level).

When `security_qos_flags` is not set, a malicious program can gain the
elevated privileges of a privileged Rust process when it allows opening
user-specified paths, by tricking it into opening a named pipe. So
arguably `security_qos_flags` should also be set when opening arbitrary
paths. However the bits can then conflict with other flags, specifically
`FILE_FLAG_OPEN_NO_RECALL`.

For information about possible values, see [Impersonation Levels] on the
Windows Dev Center site. The `SECURITY_SQOS_PRESENT` flag is set
automatically when using this method.

### tokio::security_qos_flags (function) › Examples

```no_run
use windows_sys::Win32::Storage::FileSystem::SECURITY_IDENTIFICATION;
use tokio::fs::OpenOptions;

# #[tokio::main]
# async fn main() -> std::io::Result<()> {
let file = OpenOptions::new()
    .write(true)
    .create(true)

    // Sets the flag value to `SecurityIdentification`.
    .security_qos_flags(SECURITY_IDENTIFICATION)

    .open(r"\\.\pipe\MyPipe").await?;
# Ok(())
# }
```

[`CreateFile`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea
[`CreateFile2`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfile2
[Impersonation Levels]:
    https://docs.microsoft.com/en-us/windows/win32/api/winnt/ne-winnt-security_impersonation_level

## tokio::seek (function)

Creates a future which will seek an IO object, and then yield the
new position in the object and the object itself.

Equivalent to:

```ignore
async fn seek(&mut self, pos: SeekFrom) -> io::Result<u64>;
```

In the case of an error the buffer and the object will be discarded, with
the error yielded.

### tokio::seek (function) › Examples

```no_run
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::fs::File;
use tokio::io::{AsyncSeekExt, AsyncReadExt};

use std::io::SeekFrom;

# async fn dox() -> std::io::Result<()> {
let mut file = File::open("foo.txt").await?;
file.seek(SeekFrom::Start(6)).await?;

let mut contents = vec![0u8; 10];
file.read_exact(&mut contents).await?;
# Ok(())
# }
# }
```

## tokio::select (macro)

Waits on multiple concurrent branches, returning when the **first** branch
completes, cancelling the remaining branches.

The `select!` macro must be used inside of async functions, closures, and
blocks.

The `select!` macro accepts one or more branches with the following pattern:

```text
<pattern> = <async expression> (, if <precondition>)? => <handler>,
```

Additionally, the `select!` macro may include a single, optional `else`
branch, which evaluates if none of the other branches match their patterns:

```text
else => <expression>
```

The macro aggregates all `<async expression>` expressions and runs them
concurrently on the **current** task. Once the **first** expression
completes with a value that matches its `<pattern>`, the `select!` macro
returns the result of evaluating the completed branch's `<handler>`
expression.

Additionally, each branch may include an optional `if` precondition. If the
precondition returns `false`, then the branch is disabled. The provided
`<async expression>` is still evaluated but the resulting future is never
polled. This capability is useful when using `select!` within a loop.

The complete lifecycle of a `select!` expression is as follows:

1. Evaluate all provided `<precondition>` expressions. If the precondition
   returns `false`, disable the branch for the remainder of the current call
   to `select!`. Re-entering `select!` due to a loop clears the "disabled"
   state.
2. Aggregate the `<async expression>`s from each branch, including the
   disabled ones. If the branch is disabled, `<async expression>` is still
   evaluated, but the resulting future is not polled.
3. If **all** branches are disabled: go to step 6.
4. Concurrently await on the results for all remaining `<async expression>`s.
5. Once an `<async expression>` returns a value, attempt to apply the value to the
   provided `<pattern>`. If the pattern matches, evaluate the `<handler>` and return.
   If the pattern **does not** match, disable the current branch for the remainder of
   the current call to `select!`. Continue from step 3.
6. Evaluate the `else` expression. If no else expression is provided, panic.

### tokio::select (macro) › Runtime characteristics

By running all async expressions on the current task, the expressions are
able to run **concurrently** but not in **parallel**. This means all
expressions are run on the same thread and if one branch blocks the thread,
all other expressions will be unable to continue. If parallelism is
required, spawn each async expression using [`tokio::spawn`] and pass the
join handle to `select!`.

[`tokio::spawn`]: crate::spawn

### tokio::select (macro) › Fairness

By default, `select!` randomly picks a branch to check first. This provides
some level of fairness when calling `select!` in a loop with branches that
are always ready.

This behavior can be overridden by adding `biased;` to the beginning of the
macro usage. See the examples for details. This will cause `select` to poll
the futures in the order they appear from top to bottom. There are a few
reasons you may want this:

- The random number generation of `tokio::select!` has a non-zero CPU cost
- Your futures may interact in a way where known polling order is significant

But there is an important caveat to this mode. It becomes your responsibility
to ensure that the polling order of your futures is fair. If for example you
are selecting between a stream and a shutdown future, and the stream has a
huge volume of messages and zero or nearly zero time between them, you should
place the shutdown future earlier in the `select!` list to ensure that it is
always polled, and will not be ignored due to the stream being constantly
ready.

### tokio::select (macro) › Panics

The `select!` macro panics if all branches are disabled **and** there is no
provided `else` branch. A branch is disabled when the provided `if`
precondition returns `false` **or** when the pattern does not match the
result of `<async expression>`.

### tokio::select (macro) › Cancellation safety

When using `select!` in a loop to receive messages from multiple sources,
you should make sure that the receive call is cancellation safe to avoid
losing messages. This section goes through various common methods and
describes whether they are cancel safe.  The lists in this section are not
exhaustive.

Cancellation safety describes what happens when a future is dropped
before it completes. Whether something is cancellation safe depends on
the behavior of the future passed to `select!`, which may come from an
async method, an async expression, or another future-producing operation.

The following methods are cancellation safe:

 * [`tokio::sync::mpsc::Receiver::recv`](crate::sync::mpsc::Receiver::recv)
 * [`tokio::sync::mpsc::UnboundedReceiver::recv`](crate::sync::mpsc::UnboundedReceiver::recv)
 * [`tokio::sync::broadcast::Receiver::recv`](crate::sync::broadcast::Receiver::recv)
 * [`tokio::sync::watch::Receiver::changed`](crate::sync::watch::Receiver::changed)
 * [`tokio::net::TcpListener::accept`](crate::net::TcpListener::accept)
 * [`tokio::net::UnixListener::accept`](crate::net::UnixListener::accept)
 * [`tokio::signal::unix::Signal::recv`](crate::signal::unix::Signal::recv)
 * [`tokio::io::AsyncReadExt::read`](crate::io::AsyncReadExt::read) on any `AsyncRead`
 * [`tokio::io::AsyncReadExt::read_buf`](crate::io::AsyncReadExt::read_buf) on any `AsyncRead`
 * [`tokio::io::AsyncWriteExt::write`](crate::io::AsyncWriteExt::write) on any `AsyncWrite`
 * [`tokio::io::AsyncWriteExt::write_buf`](crate::io::AsyncWriteExt::write_buf) on any `AsyncWrite`
 * [`tokio_stream::StreamExt::next`](https://docs.rs/tokio-stream/0.1/tokio_stream/trait.StreamExt.html#method.next) on any `Stream`
 * [`futures::stream::StreamExt::next`](https://docs.rs/futures/0.3/futures/stream/trait.StreamExt.html#method.next) on any `Stream`

The following methods are not cancellation safe and can lead to loss of data:

 * [`tokio::io::AsyncReadExt::read_exact`](crate::io::AsyncReadExt::read_exact)
 * [`tokio::io::AsyncReadExt::read_to_end`](crate::io::AsyncReadExt::read_to_end)
 * [`tokio::io::AsyncReadExt::read_to_string`](crate::io::AsyncReadExt::read_to_string)
 * [`tokio::io::AsyncWriteExt::write_all`](crate::io::AsyncWriteExt::write_all)

The following methods are not cancellation safe because they use a queue for
fairness and cancellation makes you lose your place in the queue:

 * [`tokio::sync::Mutex::lock`](crate::sync::Mutex::lock)
 * [`tokio::sync::RwLock::read`](crate::sync::RwLock::read)
 * [`tokio::sync::RwLock::write`](crate::sync::RwLock::write)
 * [`tokio::sync::Semaphore::acquire`](crate::sync::Semaphore::acquire)
 * [`tokio::sync::Notify::notified`](crate::sync::Notify::notified)

To determine whether your own methods are cancellation safe, look for the
location of uses of `.await`. This is because when an asynchronous method is
cancelled, that always happens at an `.await`. If your function behaves
correctly even if it is restarted while waiting at an `.await`, then it is
cancellation safe.

Cancellation safety can be defined in the following way: If you have a
future that has not yet completed, then it must be a no-op to drop that
future and recreate it. This definition is motivated by the situation where
a `select!` is used in a loop. Without this guarantee, you would lose your
progress when another branch completes and you restart the `select!` by
going around the loop.

Be aware that cancelling something that is not cancellation safe is not
necessarily wrong. For example, if you are cancelling a task because the
application is shutting down, then you probably don't care that partially
read data is lost.

### tokio::select (macro) › Examples

Basic select with two branches.

```
async fn do_stuff_async() {
    // async work
}

async fn more_async_work() {
    // more here
}

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
tokio::select! {
    _ = do_stuff_async() => {
        println!("do_stuff_async() completed first")
    }
    _ = more_async_work() => {
        println!("more_async_work() completed first")
    }
};
# }
```

Basic stream selecting.

```
use tokio_stream::{self as stream, StreamExt};

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let mut stream1 = stream::iter(vec![1, 2, 3]);
let mut stream2 = stream::iter(vec![4, 5, 6]);

let next = tokio::select! {
    v = stream1.next() => v.unwrap(),
    v = stream2.next() => v.unwrap(),
};

assert!(next == 1 || next == 4);
# }
```

Collect the contents of two streams. In this example, we rely on pattern
matching and the fact that `stream::iter` is "fused", i.e. once the stream
is complete, all calls to `next()` return `None`.

```
use tokio_stream::{self as stream, StreamExt};

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let mut stream1 = stream::iter(vec![1, 2, 3]);
let mut stream2 = stream::iter(vec![4, 5, 6]);

let mut values = vec![];

loop {
    tokio::select! {
        Some(v) = stream1.next() => values.push(v),
        Some(v) = stream2.next() => values.push(v),
        else => break,
    }
}

values.sort();
assert_eq!(&[1, 2, 3, 4, 5, 6], &values[..]);
# }
```

Using the same future in multiple `select!` expressions can be done by passing
a reference to the future. Doing so requires the future to be [`Unpin`]. A
future can be made [`Unpin`] by either using [`Box::pin`] or stack pinning.

[`Unpin`]: std::marker::Unpin
[`Box::pin`]: std::boxed::Box::pin

Here, a stream is consumed for at most 1 second.

```
use tokio_stream::{self as stream, StreamExt};
use tokio::time::{self, Duration};

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let mut stream = stream::iter(vec![1, 2, 3]);
let sleep = time::sleep(Duration::from_secs(1));
tokio::pin!(sleep);

loop {
    tokio::select! {
        maybe_v = stream.next() => {
            if let Some(v) = maybe_v {
                println!("got = {}", v);
            } else {
                break;
            }
        }
        _ = &mut sleep => {
            println!("timeout");
            break;
        }
    }
}
# }
```

Joining two values using `select!`.

```
use tokio::sync::oneshot;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx1, mut rx1) = oneshot::channel();
let (tx2, mut rx2) = oneshot::channel();

tokio::spawn(async move {
    tx1.send("first").unwrap();
});

tokio::spawn(async move {
    tx2.send("second").unwrap();
});

let mut a = None;
let mut b = None;

while a.is_none() || b.is_none() {
    tokio::select! {
        v1 = (&mut rx1), if a.is_none() => a = Some(v1.unwrap()),
        v2 = (&mut rx2), if b.is_none() => b = Some(v2.unwrap()),
    }
}

let res = (a.unwrap(), b.unwrap());

assert_eq!(res.0, "first");
assert_eq!(res.1, "second");
# }
```

Using the `biased;` mode to control polling order.

```
# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let mut count = 0u8;

loop {
    tokio::select! {
        // If you run this example without `biased;`, the polling order is
        // pseudo-random, and the assertions on the value of count will
        // (probably) fail.
        biased;

        _ = async {}, if count < 1 => {
            count += 1;
            assert_eq!(count, 1);
        }
        _ = async {}, if count < 2 => {
            count += 1;
            assert_eq!(count, 2);
        }
        _ = async {}, if count < 3 => {
            count += 1;
            assert_eq!(count, 3);
        }
        _ = async {}, if count < 4 => {
            count += 1;
            assert_eq!(count, 4);
        }

        else => {
            break;
        }
    };
}
# }
```

### tokio::select (macro) › Avoid racy `if` preconditions

Given that `if` preconditions are used to disable `select!` branches, some
caution must be used to avoid missing values.

For example, here is **incorrect** usage of `sleep` with `if`. The objective
is to repeatedly run an asynchronous task for up to 50 milliseconds.
However, there is a potential for the `sleep` completion to be missed.

```no_run,should_panic
use tokio::time::{self, Duration};

async fn some_async_work() {
    // do work
}

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let sleep = time::sleep(Duration::from_millis(50));
tokio::pin!(sleep);

while !sleep.is_elapsed() {
    tokio::select! {
        _ = &mut sleep, if !sleep.is_elapsed() => {
            println!("operation timed out");
        }
        _ = some_async_work() => {
            println!("operation completed");
        }
    }
}

panic!("This example shows how not to do it!");
# }
```

In the above example, `sleep.is_elapsed()` may return `true` even if
`sleep.poll()` never returned `Ready`. This opens up a potential race
condition where `sleep` expires between the `while !sleep.is_elapsed()`
check and the call to `select!` resulting in the `some_async_work()` call to
run uninterrupted despite the sleep having elapsed.

One way to write the above example without the race would be:

```
use tokio::time::{self, Duration};

async fn some_async_work() {
# time::sleep(Duration::from_millis(10)).await;
    // do work
}

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let sleep = time::sleep(Duration::from_millis(50));
tokio::pin!(sleep);

loop {
    tokio::select! {
        _ = &mut sleep => {
            println!("operation timed out");
            break;
        }
        _ = some_async_work() => {
            println!("operation completed");
        }
    }
}
# }
```
### tokio::select (macro) › Alternatives from the Ecosystem

The `select!` macro is a powerful tool for managing multiple asynchronous
branches, enabling tasks to run concurrently within the same thread. However,
its use can introduce challenges, particularly around cancellation safety, which
can lead to subtle and hard-to-debug errors. For many use cases, ecosystem
alternatives may be preferable as they mitigate these concerns by offering
clearer syntax, more predictable control flow, and reducing the need to manually
handle issues like fuse semantics or cancellation safety.

### tokio::select (macro) › Merging Streams

For cases where `loop { select! { ... } }` is used to poll multiple tasks,
stream merging offers a concise alternative, inherently handle cancellation-safe
processing, removing the risk of data loss. Libraries such as [`tokio_stream`],
[`futures::stream`] and [`futures_concurrency`] provide tools for merging
streams and handling their outputs sequentially.

[`tokio_stream`]: https://docs.rs/tokio-stream/latest/tokio_stream/
[`futures::stream`]: https://docs.rs/futures/latest/futures/stream/
[`futures_concurrency`]: https://docs.rs/futures-concurrency/latest/futures_concurrency/

### tokio::select (macro) › Example with `select!`

```
struct File;
struct Channel;
struct Socket;

impl Socket {
    async fn read_packet(&mut self) -> Vec<u8> {
        vec![]
    }
}

async fn read_send(_file: &mut File, _channel: &mut Channel) {
    // do work that is not cancel safe
}

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
// open our IO types
let mut file = File;
let mut channel = Channel;
let mut socket = Socket;

loop {
    tokio::select! {
        _ = read_send(&mut file, &mut channel) => { /* ... */ },
        _data = socket.read_packet() => { /* ... */ }
        _ = futures::future::ready(()) => break
    }
}
# }
```

### tokio::select (macro) › Moving to `merge`

By using merge, you can unify multiple asynchronous tasks into a single stream,
eliminating the need to manage tasks manually and reducing the risk of
unintended behavior like data loss.

```
use std::pin::pin;

use futures::stream::unfold;
use tokio_stream::StreamExt;

struct File;
struct Channel;
struct Socket;

impl Socket {
    async fn read_packet(&mut self) -> Vec<u8> {
        vec![]
    }
}

async fn read_send(_file: &mut File, _channel: &mut Channel) {
    // do work that is not cancel safe
}

enum Message {
    Stop,
    Sent,
    Data(Vec<u8>),
}

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
// open our IO types
let file = File;
let channel = Channel;
let socket = Socket;

let a = unfold((file, channel), |(mut file, mut channel)| async {
    read_send(&mut file, &mut channel).await;
    Some((Message::Sent, (file, channel)))
});
let b = unfold(socket, |mut socket| async {
    let data = socket.read_packet().await;
    Some((Message::Data(data), socket))
});
let c = tokio_stream::iter([Message::Stop]);

let mut s = pin!(a.merge(b).merge(c));
while let Some(msg) = s.next().await {
    match msg {
        Message::Data(_data) => { /* ... */ }
        Message::Sent => continue,
        Message::Stop => break,
    }
}
# }
```

### tokio::select (macro) › Racing Futures

If you need to wait for the first completion among several asynchronous tasks,
ecosystem utilities such as
[`futures`](https://docs.rs/futures/latest/futures/),
[`futures-lite`](https://docs.rs/futures-lite/latest/futures_lite/) or
[`futures-concurrency`](https://docs.rs/futures-concurrency/latest/futures_concurrency/)
provide streamlined syntax for racing futures:

- [`futures_concurrency::future::Race`](https://docs.rs/futures-concurrency/latest/futures_concurrency/future/trait.Race.html)
- [`futures::select`](https://docs.rs/futures/latest/futures/macro.select.html)
- [`futures::stream::select_all`](https://docs.rs/futures/latest/futures/stream/select_all/index.html) (for streams)
- [`futures_lite::future::or`](https://docs.rs/futures-lite/latest/futures_lite/future/fn.or.html)
- [`futures_lite::future::race`](https://docs.rs/futures-lite/latest/futures_lite/future/fn.race.html)

```
use futures_concurrency::future::Race;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let task_a = async { Ok("ok") };
let task_b = async { Err("error") };
let result = (task_a, task_b).race().await;

match result {
    Ok(output) => println!("First task completed with: {output}"),
    Err(err) => eprintln!("Error occurred: {err}"),
}
# }
```

## tokio::semaphore (function)

Returns the [`Semaphore`] from which this permit was acquired.

## tokio::send (function)

Attempts to send a message on this `UnboundedSender` without blocking.

This method is not marked as `async` because sending a message to an unbounded channel
never requires any form of waiting. This is due to the channel's infinite capacity,
allowing the `send` operation to complete immediately. As a result, the `send` method can be
used in both synchronous and asynchronous code without issues.

If the receive half of the channel is closed, either due to [`close`]
being called or the [`UnboundedReceiver`] having been dropped, this
function returns an error. The error includes the value passed to `send`.

[`close`]: UnboundedReceiver::close
[`UnboundedReceiver`]: UnboundedReceiver

## tokio::send (function)

Attempts to send a value on this channel, returning it back if it could
not be sent.

This method consumes `self` as only one value may ever be sent on a `oneshot`
channel. It is not marked async because sending a message to a `oneshot`
channel never requires any form of waiting.  Because of this, the `send`
method can be used in both synchronous and asynchronous code without
problems.

A successful send occurs when it is determined that the other end of the
channel has not hung up already. An unsuccessful send would be one where
the corresponding receiver has already been deallocated. Note that a
return value of `Err` means that the data will never be received, but
a return value of `Ok` does *not* mean that the data will be received.
It is possible for the corresponding receiver to hang up immediately
after this function returns `Ok`.

### tokio::send (function) › Examples

Send a value to another task

```
use tokio::sync::oneshot;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, rx) = oneshot::channel();

tokio::spawn(async move {
    if let Err(_) = tx.send(3) {
        println!("the receiver dropped");
    }
});

match rx.await {
    Ok(v) => println!("got = {:?}", v),
    Err(_) => println!("the sender dropped"),
}
# }
```

## tokio::send (function)

Attempts to send a value to all active [`Receiver`] handles, returning
it back if it could not be sent.

A successful send occurs when there is at least one active [`Receiver`]
handle. An unsuccessful send would be one where all associated
[`Receiver`] handles have already been dropped.

### tokio::send (function) › Return

On success, the number of subscribed [`Receiver`] handles is returned.
This does not mean that this number of receivers will see the message as
a receiver may drop or lag ([see lagging](self#lagging)) before receiving
the message.

### tokio::send (function) › Note

A return value of `Ok` **does not** mean that the sent value will be
observed by all or any of the active [`Receiver`] handles. [`Receiver`]
handles may be dropped before receiving the sent message.

A return value of `Err` **does not** mean that future calls to `send`
will fail. New [`Receiver`] handles may be created by calling
[`subscribe`].

[`Receiver`]: crate::sync::broadcast::Receiver
[`subscribe`]: crate::sync::broadcast::Sender::subscribe

### tokio::send (function) › Examples

```
use tokio::sync::broadcast;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx1) = broadcast::channel(16);
let mut rx2 = tx.subscribe();

tokio::spawn(async move {
    assert_eq!(rx1.recv().await.unwrap(), 10);
    assert_eq!(rx1.recv().await.unwrap(), 20);
});

tokio::spawn(async move {
    assert_eq!(rx2.recv().await.unwrap(), 10);
    assert_eq!(rx2.recv().await.unwrap(), 20);
});

tx.send(10).unwrap();
tx.send(20).unwrap();
# }
```

## tokio::send (function)

Sends a new value via the channel, notifying all receivers.

This method fails if the channel is closed, which is the case when
every receiver has been dropped. It is possible to reopen the channel
using the [`subscribe`] method. However, when `send` fails, the value
isn't made available for future receivers (but returned with the
[`SendError`]).

To always make a new value available for future receivers, even if no
receiver currently exists, one of the other send methods
([`send_if_modified`], [`send_modify`], or [`send_replace`]) can be
used instead.

[`subscribe`]: Sender::subscribe
[`SendError`]: error::SendError
[`send_if_modified`]: Sender::send_if_modified
[`send_modify`]: Sender::send_modify
[`send_replace`]: Sender::send_replace

## tokio::send (function)

Sends a value using the reserved capacity.

Capacity for the message has already been reserved. The message is sent
to the receiver and the permit is consumed. The operation will succeed
even if the receiver half has been closed. See [`Receiver::close`] for
more details on performing a clean shutdown.

Unlike [`Permit::send`], this method returns the [`Sender`] from which
the `OwnedPermit` was reserved.

[`Receiver::close`]: Receiver::close

### tokio::send (function) › Examples

```
use tokio::sync::mpsc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = mpsc::channel(1);

// Reserve capacity
let permit = tx.reserve_owned().await.unwrap();

// Send a message on the permit, returning the sender.
let tx = permit.send(456);

// The value sent on the permit is received
assert_eq!(rx.recv().await.unwrap(), 456);

// We may now reuse `tx` to send another message.
tx.send(789).await.unwrap();
# }
```

## tokio::send (function)

Sends a value using the reserved capacity.

Capacity for the message has already been reserved. The message is sent
to the receiver and the permit is consumed. The operation will succeed
even if the receiver half has been closed. See [`Receiver::close`] for
more details on performing a clean shutdown.

[`Receiver::close`]: Receiver::close

### tokio::send (function) › Examples

```
use tokio::sync::mpsc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = mpsc::channel(1);

// Reserve capacity
let permit = tx.reserve().await.unwrap();

// Trying to send directly on the `tx` will fail due to no
// available capacity.
assert!(tx.try_send(123).is_err());

// Send a message on the permit
permit.send(456);

// The value sent on the permit is received
assert_eq!(rx.recv().await.unwrap(), 456);
# }
```

## tokio::send (function)

Sends a value, waiting until there is capacity.

A successful send occurs when it is determined that the other end of the
channel has not hung up already. An unsuccessful send would be one where
the corresponding receiver has already been closed. Note that a return
value of `Err` means that the data will never be received, but a return
value of `Ok` does not mean that the data will be received. It is
possible for the corresponding receiver to hang up immediately after
this function returns `Ok`.

### tokio::send (function) › Errors

If the receive half of the channel is closed, either due to [`close`]
being called or the [`Receiver`] handle dropping, the function returns
an error. The error includes the value passed to `send`.

[`close`]: Receiver::close
[`Receiver`]: Receiver

### tokio::send (function) › Cancel safety

If `send` is used as a branch in [`tokio::select!`](crate::select) and
another branch completes first, then it is guaranteed
that the message was not sent. **However, in that case, the message
is dropped and will be lost.**

To avoid losing messages, use [`reserve`](Self::reserve) to reserve
capacity, then use the returned [`Permit`] to send the message.

This channel uses a queue to ensure that calls to `send` and `reserve`
complete in the order they were requested.  Cancelling a call to
`send` makes you lose your place in the queue.

### tokio::send (function) › Examples

In the following example, each call to `send` will block until the
previously sent value was received.

```rust
use tokio::sync::mpsc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = mpsc::channel(1);

tokio::spawn(async move {
    for i in 0..10 {
        if let Err(_) = tx.send(i).await {
            println!("receiver dropped");
            return;
        }
    }
});

while let Some(i) = rx.recv().await {
    println!("got = {}", i);
}
# }
```

## tokio::send (function)

Sends data on the socket to the remote address that the socket is
connected to.

The [`connect`] method will connect this socket to a remote address.
This method will fail if the socket is not connected.

This method may fail with a [`ConnectionRefused`] error if the remote
address has replied with ICMP Unreachable to a previously sent packet.
However, this behavior depends on the OS.

[`connect`]: method@Self::connect
[`ConnectionRefused`]: std::io::ErrorKind::ConnectionRefused

### tokio::send (function) › Return

On success, the number of bytes sent is returned, otherwise, the
encountered error is returned.

### tokio::send (function) › Cancel safety

This method is cancel safe. If `send` is used as a branch in
[`tokio::select!`](crate::select) and another branch
completes first, then it is guaranteed that the message was not sent.

### tokio::send (function) › Examples

```no_run
use tokio::io;
use tokio::net::UdpSocket;

#[tokio::main]
async fn main() -> io::Result<()> {
    // Bind socket
    let socket = UdpSocket::bind("127.0.0.1:8080").await?;
    socket.connect("127.0.0.1:8081").await?;

    // Send a message
    socket.send(b"hello world").await?;

    Ok(())
}
```

## tokio::send_buffer_size (function)

Returns the size of the TCP send buffer for this socket.

On most operating systems, this is the value of the `SO_SNDBUF` socket
option.

Note that if [`set_send_buffer_size`] has been called on this socket
previously, the value returned by this function may not be the same as
the argument provided to `set_send_buffer_size`. This is for the
following reasons:

* Most operating systems have minimum and maximum allowed sizes for the
  send buffer, and will clamp the provided value if it is below the
  minimum or above the maximum. The minimum and maximum buffer sizes are
  OS-dependent.
* Linux will double the buffer size to account for internal bookkeeping
  data, and returns the doubled value from `getsockopt(2)`. As per `man
  7 socket`:
  > Sets or gets the maximum socket send buffer in bytes. The
  > kernel doubles this value (to allow space for bookkeeping
  > overhead) when it is set using `setsockopt(2)`, and this doubled
  > value is returned by `getsockopt(2)`.

[`set_send_buffer_size`]: #method.set_send_buffer_size

## tokio::send_if_modified (function)

Modifies the watched value **conditionally** in-place,
notifying all receivers only if modified.

This can be useful for modifying the watched value, without
having to allocate a new instance. Additionally, this
method permits sending values even when there are no receivers.

The `modify` closure must return `true` if the value has actually
been modified during the mutable borrow. It should only return `false`
if the value is guaranteed to be unmodified despite the mutable
borrow.

Receivers are only notified if the closure returned `true`. If the
closure has modified the value but returned `false` this results
in a *silent modification*, i.e. the modified value will be visible
in subsequent calls to `borrow`, but receivers will not receive
a change notification.

Returns the result of the closure, i.e. `true` if the value has
been modified and `false` otherwise.

### tokio::send_if_modified (function) › Panics

This function panics when the invocation of the `modify` closure panics.
No receivers are notified when panicking. All changes of the watched
value applied by the closure before panicking will be visible in
subsequent calls to `borrow`.

### tokio::send_if_modified (function) › Examples

```
use tokio::sync::watch;

struct State {
    counter: usize,
}
let (state_tx, mut state_rx) = watch::channel(State { counter: 1 });
let inc_counter_if_odd = |state: &mut State| {
    if state.counter % 2 == 1 {
        state.counter += 1;
        return true;
    }
    false
};

assert_eq!(state_rx.borrow().counter, 1);

assert!(!state_rx.has_changed().unwrap());
assert!(state_tx.send_if_modified(inc_counter_if_odd));
assert!(state_rx.has_changed().unwrap());
assert_eq!(state_rx.borrow_and_update().counter, 2);

assert!(!state_rx.has_changed().unwrap());
assert!(!state_tx.send_if_modified(inc_counter_if_odd));
assert!(!state_rx.has_changed().unwrap());
assert_eq!(state_rx.borrow_and_update().counter, 2);
```

## tokio::send_modify (function)

Modifies the watched value **unconditionally** in-place,
notifying all receivers.

This can be useful for modifying the watched value, without
having to allocate a new instance. Additionally, this
method permits sending values even when there are no receivers.

Prefer to use the more versatile function [`Self::send_if_modified()`]
if the value is only modified conditionally during the mutable borrow
to prevent unneeded change notifications for unmodified values.

### tokio::send_modify (function) › Panics

This function panics when the invocation of the `modify` closure panics.
No receivers are notified when panicking. All changes of the watched
value applied by the closure before panicking will be visible in
subsequent calls to `borrow`.

### tokio::send_modify (function) › Examples

```
use tokio::sync::watch;

struct State {
    counter: usize,
}
let (state_tx, state_rx) = watch::channel(State { counter: 0 });
state_tx.send_modify(|state| state.counter += 1);
assert_eq!(state_rx.borrow().counter, 1);
```

## tokio::send_replace (function)

Sends a new value via the channel, notifying all receivers and returning
the previous value in the channel.

This can be useful for reusing the buffers inside a watched value.
Additionally, this method permits sending values even when there are no
receivers.

### tokio::send_replace (function) › Examples

```
use tokio::sync::watch;

let (tx, _rx) = watch::channel(1);
assert_eq!(tx.send_replace(2), 1);
assert_eq!(tx.send_replace(3), 2);
```

## tokio::send_timeout (function)

Sends a value, waiting until there is capacity, but only for a limited time.

Shares the same success and error conditions as [`send`], adding one more
condition for an unsuccessful send, which is when the provided timeout has
elapsed, and there is no capacity available.

[`send`]: Sender::send

### tokio::send_timeout (function) › Errors

If the receive half of the channel is closed, either due to [`close`]
being called or the [`Receiver`] having been dropped,
the function returns an error. The error includes the value passed to `send`.

[`close`]: Receiver::close
[`Receiver`]: Receiver

### tokio::send_timeout (function) › Panics

This function panics if it is called outside the context of a Tokio
runtime [with time enabled](crate::runtime::Builder::enable_time).

### tokio::send_timeout (function) › Examples

In the following example, each call to `send_timeout` will block until the
previously sent value was received, unless the timeout has elapsed.

```rust
use tokio::sync::mpsc;
use tokio::time::{sleep, Duration};

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = mpsc::channel(1);

tokio::spawn(async move {
    for i in 0..10 {
        if let Err(e) = tx.send_timeout(i, Duration::from_millis(100)).await {
            println!("send error: #{:?}", e);
            return;
        }
    }
});

while let Some(i) = rx.recv().await {
    println!("got = {}", i);
    sleep(Duration::from_millis(200)).await;
}
# }
```

## tokio::send_to (function)

Sends data on the socket to the given address. On success, returns the
number of bytes written.

Address type can be any implementer of [`ToSocketAddrs`] trait. See its
documentation for concrete examples.

It is possible for `addr` to yield multiple addresses, but `send_to`
will only send data to the first address yielded by `addr`.

This will return an error when the IP version of the local socket does
not match that returned from [`ToSocketAddrs`].

[`ToSocketAddrs`]: crate::net::ToSocketAddrs

### tokio::send_to (function) › Cancel safety

This method is cancel safe. If `send_to` is used as a branch in
[`tokio::select!`](crate::select) and another branch
completes first, then it is guaranteed that the message was not sent.

### tokio::send_to (function) › Example

```no_run
use tokio::net::UdpSocket;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let socket = UdpSocket::bind("127.0.0.1:8080").await?;
    let len = socket.send_to(b"hello world", "127.0.0.1:8081").await?;

    println!("Sent {} bytes", len);

    Ok(())
}
```

## tokio::sender_count (function)

Returns the number of senders that currently exist.

### tokio::sender_count (function) › Examples

```
use tokio::sync::watch;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx1, rx) = watch::channel("hello");

assert_eq!(1, tx1.sender_count());

let tx2 = tx1.clone();

assert_eq!(2, tx1.sender_count());
assert_eq!(2, tx2.sender_count());
# }
```

## tokio::sender_strong_count (function)

Returns the number of [`Sender`] handles.

## tokio::sender_strong_count (function)

Returns the number of [`Sender`] handles.

## tokio::sender_strong_count (function)

Returns the number of [`UnboundedSender`] handles.

## tokio::sender_weak_count (function)

Returns the number of [`WeakSender`] handles.

## tokio::sender_weak_count (function)

Returns the number of [`WeakSender`] handles.

## tokio::sender_weak_count (function)

Returns the number of [`WeakUnboundedSender`] handles.

## tokio::set (function)

Sets the value of the `OnceCell` to the given value if the `OnceCell` is
empty.

If the `OnceCell` already has a value, this call will fail with an
[`SetError::AlreadyInitializedError`].

If the `OnceCell` is empty, but some other task is currently trying to
set the value, this call will fail with [`SetError::InitializingError`].

[`SetError::AlreadyInitializedError`]: crate::sync::SetError::AlreadyInitializedError
[`SetError::InitializingError`]: crate::sync::SetError::InitializingError

## tokio::set (function)

Sets the value of the `SetOnce` to the given value if the `SetOnce` is
empty.

If the `SetOnce` already has a value, this call will fail with an
[`SetOnceError`].

[`SetOnceError`]: crate::sync::SetOnceError

## tokio::set_broadcast (function)

Sets the value of the `SO_BROADCAST` option for this socket.

When enabled, this socket is allowed to send packets to a broadcast
address.

## tokio::set_filled (function)

Sets the size of the filled region of the buffer.

The number of initialized bytes is not changed.

Note that this can be used to *shrink* the filled region of the buffer in addition to growing it (for
example, by a `AsyncRead` implementation that compresses data in-place).

### tokio::set_filled (function) › Panics

Panics if the filled region of the buffer would become larger than the initialized region.

## tokio::set_keepalive (function)

Sets value for the `SO_KEEPALIVE` option on this socket.

## tokio::set_len (function)

Truncates or extends the underlying file, updating the size of this file to become size.

If the size is less than the current file's size, then the file will be
shrunk. If it is greater than the current file's size, then the file
will be extended to size and have all of the intermediate data filled in
with 0s.

### tokio::set_len (function) › Errors

This function will return an error if the file is not opened for
writing.

### tokio::set_len (function) › Examples

```no_run
use tokio::fs::File;
use tokio::io::AsyncWriteExt;

# async fn dox() -> std::io::Result<()> {
let mut file = File::create("foo.txt").await?;
file.write_all(b"hello, world!").await?;
file.set_len(10).await?;
# Ok(())
# }
```

The [`write_all`] method is defined on the [`AsyncWriteExt`] trait.

[`write_all`]: fn@crate::io::AsyncWriteExt::write_all
[`AsyncWriteExt`]: trait@crate::io::AsyncWriteExt

## tokio::set_limit (function)

Sets the number of bytes that can be read before this instance will
return EOF. This is the same as constructing a new `Take` instance, so
the amount of bytes read and the previous limit value don't matter when
calling this method.

## tokio::set_linger (function)

Sets the linger duration of this socket by setting the `SO_LINGER` option.

This option controls the action taken when a stream has unsent messages and the stream is
closed. If `SO_LINGER` is set, the system shall block the process until it can transmit the
data or until the time expires.

If `SO_LINGER` is not specified, and the socket is closed, the system handles the call in a
way that allows the process to continue as quickly as possible.

This option is deprecated because setting `SO_LINGER` on a socket used with Tokio is always
incorrect as it leads to blocking the thread when the socket is closed. For more details,
please see:

> Volumes of communications have been devoted to the intricacies of `SO_LINGER` versus
> non-blocking (`O_NONBLOCK`) sockets. From what I can tell, the final word is: don't do
> it. Rely on the `shutdown()`-followed-by-`read()`-eof technique instead.
>
> From [The ultimate `SO_LINGER` page, or: why is my tcp not reliable](https://blog.netherlabs.nl/articles/2009/01/18/the-ultimate-so_linger-page-or-why-is-my-tcp-not-reliable)

Although this method is deprecated, it will not be removed from Tokio.

Note that the special case of setting `SO_LINGER` to zero does not lead to blocking. Tokio
provides [`set_zero_linger`](Self::set_zero_linger) for this purpose.

## tokio::set_linger (function)

Sets the linger duration of this socket by setting the `SO_LINGER` option.

This option controls the action taken when a stream has unsent messages and the stream is
closed. If `SO_LINGER` is set, the system shall block the process until it can transmit the
data or until the time expires.

If `SO_LINGER` is not specified, and the stream is closed, the system handles the call in a
way that allows the process to continue as quickly as possible.

This option is deprecated because setting `SO_LINGER` on a socket used with Tokio is
always incorrect as it leads to blocking the thread when the socket is closed. For more
details, please see:

> Volumes of communications have been devoted to the intricacies of `SO_LINGER` versus
> non-blocking (`O_NONBLOCK`) sockets. From what I can tell, the final word is: don't
> do it. Rely on the `shutdown()`-followed-by-`read()`-eof technique instead.
>
> From [The ultimate `SO_LINGER` page, or: why is my tcp not reliable](https://blog.netherlabs.nl/articles/2009/01/18/the-ultimate-so_linger-page-or-why-is-my-tcp-not-reliable)

Although this method is deprecated, it will not be removed from Tokio.

Note that the special case of setting `SO_LINGER` to zero does not lead to blocking.
Tokio provides [`set_zero_linger`](Self::set_zero_linger) for this purpose.

### tokio::set_linger (function) › Examples

```no_run
# #![allow(deprecated)]
use tokio::net::TcpStream;

# async fn dox() -> Result<(), Box<dyn std::error::Error>> {
let stream = TcpStream::connect("127.0.0.1:8080").await?;

stream.set_linger(None)?;
# Ok(())
# }
```

## tokio::set_max_buf_size (function)

Set the maximum buffer size for the underlying [`AsyncRead`] / [`AsyncWrite`] operation.

Although Tokio uses a sensible default value for this buffer size, this function would be
useful for changing that default depending on the situation.

### tokio::set_max_buf_size (function) › Examples

```no_run
use tokio::fs::File;
use tokio::io::AsyncWriteExt;

# async fn dox() -> std::io::Result<()> {
let mut file = File::open("foo.txt").await?;

// Set maximum buffer size to 8 MiB
file.set_max_buf_size(8 * 1024 * 1024);

let mut buf = vec![1; 1024 * 1024 * 1024];

// Write the 1 GiB buffer in chunks up to 8 MiB each.
file.write_all(&mut buf).await?;
# Ok(())
# }
```

## tokio::set_missed_tick_behavior (function)

Sets the [`MissedTickBehavior`] strategy that should be used.

## tokio::set_multicast_loop_v4 (function)

Sets the value of the `IP_MULTICAST_LOOP` option for this socket.

If enabled, multicast packets will be looped back to the local socket.

### tokio::set_multicast_loop_v4 (function) › Note

This may not have any effect on IPv6 sockets.

## tokio::set_multicast_loop_v6 (function)

Sets the value of the `IPV6_MULTICAST_LOOP` option for this socket.

Controls whether this socket sees the multicast packets it sends itself.

### tokio::set_multicast_loop_v6 (function) › Note

This may not have any effect on IPv4 sockets.

## tokio::set_multicast_ttl_v4 (function)

Sets the value of the `IP_MULTICAST_TTL` option for this socket.

Indicates the time-to-live value of outgoing multicast packets for
this socket. The default value is 1 which means that multicast packets
don't leave the local network unless explicitly requested.

### tokio::set_multicast_ttl_v4 (function) › Note

This may not have any effect on IPv6 sockets.

## tokio::set_nodelay (function)

Sets the value of the `TCP_NODELAY` option on this socket.

If set, this option disables the Nagle algorithm. This means that
segments are always sent as soon as possible, even if there is only a
small amount of data. When not set, data is buffered until there is a
sufficient amount to send out, thereby avoiding the frequent sending of
small packets.

### tokio::set_nodelay (function) › Examples

```no_run
use tokio::net::TcpStream;

# async fn dox() -> Result<(), Box<dyn std::error::Error>> {
let stream = TcpStream::connect("127.0.0.1:8080").await?;

stream.set_nodelay(true)?;
# Ok(())
# }
```

## tokio::set_nodelay (function)

Sets the value of the `TCP_NODELAY` option on this socket.

If set, this option disables the Nagle algorithm. This means that segments are always
sent as soon as possible, even if there is only a small amount of data. When not set,
data is buffered until there is a sufficient amount to send out, thereby avoiding
the frequent sending of small packets.

### tokio::set_nodelay (function) › Examples

```no_run
use tokio::net::TcpSocket;

# async fn dox() -> Result<(), Box<dyn std::error::Error>> {
let socket = TcpSocket::new_v4()?;

socket.set_nodelay(true)?;
# Ok(())
# }
```

## tokio::set_permissions (function)

Changes the permissions on the underlying file.

### tokio::set_permissions (function) › Platform-specific behavior

This function currently corresponds to the `fchmod` function on Unix and
the `SetFileInformationByHandle` function on Windows. Note that, this
[may change in the future][changes].

[changes]: https://doc.rust-lang.org/std/io/index.html#platform-specific-behavior

### tokio::set_permissions (function) › Errors

This function will return an error if the user lacks permission change
attributes on the underlying file. It may also return an error in other
os-specific unspecified cases.

### tokio::set_permissions (function) › Examples

```no_run
use tokio::fs::File;

# async fn dox() -> std::io::Result<()> {
let file = File::open("foo.txt").await?;
let mut perms = file.metadata().await?.permissions();
perms.set_readonly(true);
file.set_permissions(perms).await?;
# Ok(())
# }
```

## tokio::set_quickack (function)

Enable or disable `TCP_QUICKACK`.

This flag causes Linux to eagerly send `ACK`s rather than delaying them.
Linux may reset this flag after further operations on the socket.

See [`man 7 tcp`](https://man7.org/linux/man-pages/man7/tcp.7.html) and
[TCP delayed acknowledgment](https://en.wikipedia.org/wiki/TCP_delayed_acknowledgment)
for more information.

### tokio::set_quickack (function) › Examples

```no_run
use tokio::net::TcpStream;

# async fn dox() -> Result<(), Box<dyn std::error::Error>> {
let stream = TcpStream::connect("127.0.0.1:8080").await?;

stream.set_quickack(true)?;
# Ok(())
# }
```

## tokio::set_recv_buffer_size (function)

Sets the size of the TCP receive buffer on this socket.

On most operating systems, this sets the `SO_RCVBUF` socket option.

## tokio::set_reuseaddr (function)

Allows the socket to bind to an in-use address.

Behavior is platform specific. Refer to the target platform's
documentation for more details.

### tokio::set_reuseaddr (function) › Examples

```no_run
use tokio::net::TcpSocket;

use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let addr = "127.0.0.1:8080".parse().unwrap();

    let socket = TcpSocket::new_v4()?;
    socket.set_reuseaddr(true)?;
    socket.bind(addr)?;

    let listener = socket.listen(1024)?;
# drop(listener);

    Ok(())
}
```

## tokio::set_reuseport (function)

Allows the socket to bind to an in-use port. Only available for unix systems
(excluding Solaris, Illumos, and Cygwin).

Behavior is platform specific. Refer to the target platform's
documentation for more details.

### tokio::set_reuseport (function) › Examples

```no_run
use tokio::net::TcpSocket;

use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let addr = "127.0.0.1:8080".parse().unwrap();

    let socket = TcpSocket::new_v4()?;
    socket.set_reuseport(true)?;
    socket.bind(addr)?;

    let listener = socket.listen(1024)?;
    Ok(())
}
```

## tokio::set_send_buffer_size (function)

Sets the size of the TCP send buffer on this socket.

On most operating systems, this sets the `SO_SNDBUF` socket option.

## tokio::set_tclass_v6 (function)

Sets the value for the `IPV6_TCLASS` option on this socket.

Specifies the traffic class field that is used in every packet
sent from this socket.

### tokio::set_tclass_v6 (function) › Note

This may not have any effect on IPv4 sockets.

## tokio::set_tclass_v6 (function)

Sets the value for the `IPV6_TCLASS` option on this socket.

Specifies the traffic class field that is used in every packet
sent from this socket.

### tokio::set_tclass_v6 (function) › Note

This may not have any effect on IPv4 sockets.

## tokio::set_tos_v4 (function)

Sets the value for the `IP_TOS` option on this socket.

This value sets the type-of-service field that is used in every packet
sent from this socket.

### tokio::set_tos_v4 (function) › Note

- This may not have any effect on IPv6 sockets.
- On Windows, `IP_TOS` is only supported on [Windows 8+ or
  Windows Server 2012+.](https://docs.microsoft.com/en-us/windows/win32/winsock/ipproto-ip-socket-options)

## tokio::set_tos_v4 (function)

Sets the value for the `IP_TOS` option on this socket.

This value sets the type-of-service field that is used in every packet
sent from this socket.

### tokio::set_tos_v4 (function) › Note

- This may not have any effect on IPv6 sockets.
- On Windows, `IP_TOS` is only supported on [Windows 8+ or
  Windows Server 2012+.](https://docs.microsoft.com/en-us/windows/win32/winsock/ipproto-ip-socket-options)

## tokio::set_ttl (function)

Sets the value for the `IP_TTL` option on this socket.

This value sets the time-to-live field that is used in every packet sent
from this socket.

### tokio::set_ttl (function) › Examples

```no_run
use tokio::net::TcpListener;

use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:0").await?;

    listener.set_ttl(100).expect("could not set TTL");

    Ok(())
}
```

## tokio::set_ttl (function)

Sets the value for the `IP_TTL` option on this socket.

This value sets the time-to-live field that is used in every packet sent
from this socket.

### tokio::set_ttl (function) › Examples

```no_run
use tokio::net::TcpStream;

# async fn dox() -> Result<(), Box<dyn std::error::Error>> {
let stream = TcpStream::connect("127.0.0.1:8080").await?;

stream.set_ttl(123)?;
# Ok(())
# }
```

## tokio::set_ttl (function)

Sets the value for the `IP_TTL` option on this socket.

This value sets the time-to-live field that is used in every packet sent
from this socket.

### tokio::set_ttl (function) › Examples

```no_run
use tokio::net::UdpSocket;
# use std::io;

# async fn dox() -> io::Result<()> {
let sock = UdpSocket::bind("127.0.0.1:8080").await?;
sock.set_ttl(60)?;

# Ok(())
# }
```

## tokio::set_zero_linger (function)

Sets a linger duration of zero on this socket by setting the `SO_LINGER` option.

This causes the connection to be forcefully aborted ("abortive close") when the socket
is dropped or closed. Instead of the normal TCP shutdown handshake (`FIN`/`ACK`), a TCP
`RST` (reset) segment is sent to the peer, and the socket immediately discards any
unsent data residing in the socket send buffer. This prevents the socket from entering
the `TIME_WAIT` state after closing it.

This is a destructive action. Any data currently buffered by the OS but not yet
transmitted will be lost. The peer will likely receive a "Connection Reset" error
rather than a clean end-of-stream.

See the documentation for [`set_linger`](Self::set_linger) for additional details on
how `SO_LINGER` works.

### tokio::set_zero_linger (function) › Examples

```no_run
use std::time::Duration;
use tokio::net::TcpStream;

# async fn dox() -> Result<(), Box<dyn std::error::Error>> {
let stream = TcpStream::connect("127.0.0.1:8080").await?;

stream.set_zero_linger()?;
assert_eq!(stream.linger()?, Some(Duration::ZERO));
# Ok(())
# }
```

## tokio::set_zero_linger (function)

Sets a linger duration of zero on this socket by setting the `SO_LINGER` option.

This causes the connection to be forcefully aborted ("abortive close") when the socket is
dropped or closed. Instead of the normal TCP shutdown handshake (`FIN`/`ACK`), a TCP `RST`
(reset) segment is sent to the peer, and the socket immediately discards any unsent data
residing in the socket send buffer. This prevents the socket from entering the `TIME_WAIT`
state after closing it.

This is a destructive action. Any data currently buffered by the OS but not yet transmitted
will be lost. The peer will likely receive a "Connection Reset" error rather than a clean
end-of-stream.

See the documentation for [`set_linger`](Self::set_linger) for additional details on how
`SO_LINGER` works.

## tokio::share_mode (function)

Overrides the `dwShareMode` argument to the call to [`CreateFile`] with
the specified value.

By default `share_mode` is set to
`FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE`. This allows
other processes to read, write, and delete/rename the same file
while it is open. Removing any of the flags will prevent other
processes from performing the corresponding operation until the file
handle is closed.

### tokio::share_mode (function) › Examples

```no_run
use tokio::fs::OpenOptions;

# #[tokio::main]
# async fn main() -> std::io::Result<()> {
// Do not allow others to read or modify this file while we have it open
// for writing.
let file = OpenOptions::new()
    .write(true)
    .share_mode(0)
    .open("foo.txt").await?;
# Ok(())
# }
```

[`CreateFile`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea

## tokio::shutdown (function)

Aborts all tasks and waits for them to finish shutting down.

Calling this method is equivalent to calling [`abort_all`] and then calling [`join_next`] in
a loop until it returns `None`.

This method ignores any panics in the tasks shutting down. When this call returns, the
`JoinSet` will be empty.

[`abort_all`]: fn@Self::abort_all
[`join_next`]: fn@Self::join_next

## tokio::shutdown (function)

Creates an error representing a shutdown timer.

## tokio::shutdown (function)

Shuts down the output stream, ensuring that the value can be dropped
cleanly.

Equivalent to:

```ignore
async fn shutdown(&mut self) -> io::Result<()>;
```

Similar to [`flush`], all intermediately buffered content is written to
the underlying stream. Once the operation completes, the caller should
no longer attempt to write to the stream. For example, the
`TcpStream` implementation will issue a `shutdown(Write)` sys call.

[`flush`]: fn@crate::io::AsyncWriteExt::flush

### tokio::shutdown (function) › Examples

```no_run
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::io::{self, BufWriter, AsyncWriteExt};
use tokio::fs::File;

#[tokio::main]
async fn main() -> io::Result<()> {
    let f = File::create("foo.txt").await?;
    let mut buffer = BufWriter::new(f);

    buffer.write_all(b"some bytes").await?;
    buffer.shutdown().await?;
    Ok(())
}
# }
```

## tokio::shutdown_background (function)

Shuts down the runtime, without waiting for any spawned work to stop.

This can be useful if you want to drop a runtime from within another runtime.
Normally, dropping a runtime will block indefinitely for spawned blocking tasks
to complete, which would normally not be permitted within an asynchronous context.
By calling `shutdown_background()`, you can drop the runtime from such a context.

Note however, that because we do not wait for any blocking tasks to complete, this
may result in a resource leak (in that any blocking tasks are still running until they
return.

See the [struct level documentation](Runtime#shutdown) for more details.

This function is equivalent to calling `shutdown_timeout(Duration::from_nanos(0))`.

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime::Runtime;

fn main() {
   let runtime = Runtime::new().unwrap();

   runtime.block_on(async move {
       let inner_runtime = Runtime::new().unwrap();
       // ...
       inner_runtime.shutdown_background();
   });
}
# }
```

## tokio::shutdown_background (function)

Shuts down the runtime, without waiting for any spawned work to stop.

This can be useful if you want to drop a runtime from within another runtime.
Normally, dropping a runtime will block indefinitely for spawned blocking tasks
to complete, which would normally not be permitted within an asynchronous context.
By calling `shutdown_background()`, you can drop the runtime from such a context.

Note however, that because we do not wait for any blocking tasks to complete, this
may result in a resource leak (in that any blocking tasks are still running until they
return. No other tasks will leak.

See the [struct level documentation](LocalRuntime#shutdown) for more details.

This function is equivalent to calling `shutdown_timeout(Duration::from_nanos(0))`.

```
use tokio::runtime::LocalRuntime;

fn main() {
   let runtime = LocalRuntime::new().unwrap();

   runtime.block_on(async move {
       let inner_runtime = LocalRuntime::new().unwrap();
       // ...
       inner_runtime.shutdown_background();
   });
}
```

## tokio::shutdown_timeout (function)

Shuts down the runtime, waiting for at most `duration` for all spawned
work to stop.

Note that `spawn_blocking` tasks, and only `spawn_blocking` tasks, can get left behind if
the timeout expires.

See the [struct level documentation](LocalRuntime#shutdown) for more details.

### tokio::shutdown_timeout (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime::LocalRuntime;
use tokio::task;

use std::thread;
use std::time::Duration;

fn main() {
   let runtime = LocalRuntime::new().unwrap();

   runtime.block_on(async move {
       task::spawn_blocking(move || {
           thread::sleep(Duration::from_secs(10_000));
       });
   });

   runtime.shutdown_timeout(Duration::from_millis(100));
}
# }
```

## tokio::shutdown_timeout (function)

Shuts down the runtime, waiting for at most `duration` for all spawned
work to stop.

See the [struct level documentation](Runtime#shutdown) for more details.

### tokio::shutdown_timeout (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime::Runtime;
use tokio::task;

use std::thread;
use std::time::Duration;

fn main() {
   let runtime = Runtime::new().unwrap();

   runtime.block_on(async move {
       task::spawn_blocking(move || {
           thread::sleep(Duration::from_secs(10_000));
       });
   });

   runtime.shutdown_timeout(Duration::from_millis(100));
}
# }
```

## tokio::signal::ctrl_c::ctrl_c (function)

Completes when a "ctrl-c" notification is sent to the process.

While signals are handled very differently between Unix and Windows, both
platforms support receiving a signal on "ctrl-c". This function provides a
portable API for receiving this notification.

Once the returned future is polled, a listener is registered. The future
will complete on the first received `ctrl-c` **after** the initial call to
either `Future::poll` or `.await`.

### tokio::signal::ctrl_c::ctrl_c (function) › Caveats

On Unix platforms, the first time that a `Signal` instance is registered for a
particular signal kind, an OS signal-handler is installed which replaces the
default platform behavior when that signal is received, **for the duration of
the entire process**.

For example, Unix systems will terminate a process by default when it
receives a signal generated by `"CTRL+C"` on the terminal. But, when a
`ctrl_c` stream is created to listen for this signal, the time it arrives,
it will be translated to a stream event, and the process will continue to
execute.  **Even if this `Signal` instance is dropped, subsequent `SIGINT`
deliveries will end up captured by Tokio, and the default platform behavior
will NOT be reset**.

Thus, applications should take care to ensure the expected signal behavior
occurs as expected after listening for specific signals.

### tokio::signal::ctrl_c::ctrl_c (function) › Examples

```rust,no_run
use tokio::signal;

#[tokio::main]
async fn main() {
    println!("waiting for ctrl-c");

    signal::ctrl_c().await.expect("failed to listen for event");

    println!("received ctrl-c event");
}
```

Listen in the background:

```rust,no_run
tokio::spawn(async move {
    tokio::signal::ctrl_c().await.unwrap();
    // Your handler here
});
```

## tokio::signal::unix::Signal (struct)

An listener for receiving a particular type of OS signal.

The listener can be turned into a `Stream` using [`SignalStream`].

[`SignalStream`]: https://docs.rs/tokio-stream/latest/tokio_stream/wrappers/struct.SignalStream.html

In general signal handling on Unix is a pretty tricky topic, and this
structure is no exception! There are some important limitations to keep in
mind when using `Signal` streams:

* Signals handling in Unix already necessitates coalescing signals
  together sometimes. This `Signal` stream is also no exception here in
  that it will also coalesce signals. That is, even if the signal handler
  for this process runs multiple times, the `Signal` stream may only return
  one signal notification. Specifically, before `poll` is called, all
  signal notifications are coalesced into one item returned from `poll`.
  Once `poll` has been called, however, a further signal is guaranteed to
  be yielded as an item.

  Put another way, any element pulled off the returned listener corresponds to
  *at least one* signal, but possibly more.

* Signal handling in general is relatively inefficient. Although some
  improvements are possible in this crate, it's recommended to not plan on
  having millions of signal channels open.

If you've got any questions about this feel free to open an issue on the
repo! New approaches to alleviate some of these limitations are always
appreciated!

### tokio::signal::unix::Signal (struct) › Caveats

The first time that a `Signal` instance is registered for a particular
signal kind, an OS signal-handler is installed which replaces the default
platform behavior when that signal is received, **for the duration of the
entire process**.

For example, Unix systems will terminate a process by default when it
receives `SIGINT`. But, when a `Signal` instance is created to listen for
this signal, the next `SIGINT` that arrives will be translated to a stream
event, and the process will continue to execute. **Even if this `Signal`
instance is dropped, subsequent `SIGINT` deliveries will end up captured by
Tokio, and the default platform behavior will NOT be reset**.

Thus, applications should take care to ensure the expected signal behavior
occurs as expected after listening for specific signals.

### tokio::signal::unix::Signal (struct) › Examples

Wait for `SIGHUP`

```rust,no_run
use tokio::signal::unix::{signal, SignalKind};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // An infinite stream of hangup signals.
    let mut sig = signal(SignalKind::hangup())?;

    // Print whenever a HUP signal is received
    loop {
        sig.recv().await;
        println!("got signal HUP");
    }
}
```

## tokio::signal::unix::SignalKind (struct)

Represents the specific kind of signal to listen for.

## tokio::signal::unix::signal (function)

Creates a new listener which will receive notifications when the current
process receives the specified signal `kind`.

This function will create a new stream which binds to the default reactor.
The `Signal` stream is an infinite stream which will receive
notifications whenever a signal is received. More documentation can be
found on `Signal` itself, but to reiterate:

* Signals may be coalesced beyond what the kernel already does.
* Once a signal handler is registered with the process the underlying
  libc signal handler is never unregistered.

A `Signal` stream can be created for a particular signal number
multiple times. When a signal is received then all the associated
channels will receive the signal notification.

### tokio::signal::unix::signal (function) › Errors

* If the lower-level C functions fail for some reason.
* If the previous initialization of this specific signal failed.
* If the signal is one of
  [`signal_hook::FORBIDDEN`](fn@signal_hook_registry::register#panics)

### tokio::signal::unix::signal (function) › Panics

This function panics if there is no current reactor set, or if the `rt`
feature flag is not enabled.

## tokio::signal::windows::CtrlBreak (struct)

Represents a listener which receives "ctrl-break" notifications sent to the process
via `SetConsoleCtrlHandler`.

This listener can be turned into a `Stream` using [`CtrlBreakStream`].

[`CtrlBreakStream`]: https://docs.rs/tokio-stream/latest/tokio_stream/wrappers/struct.CtrlBreakStream.html

A notification to this process notifies *all* receivers for
this event. Moreover, the notifications **are coalesced** if they aren't processed
quickly enough. This means that if two notifications are received back-to-back,
then the listener may only receive one item about the two notifications.

## tokio::signal::windows::CtrlC (struct)

Represents a listener which receives "ctrl-c" notifications sent to the process
via `SetConsoleCtrlHandler`.

This event can be turned into a `Stream` using [`CtrlCStream`].

[`CtrlCStream`]: https://docs.rs/tokio-stream/latest/tokio_stream/wrappers/struct.CtrlCStream.html

A notification to this process notifies *all* receivers for
this event. Moreover, the notifications **are coalesced** if they aren't processed
quickly enough. This means that if two notifications are received back-to-back,
then the listener may only receive one item about the two notifications.

## tokio::signal::windows::CtrlClose (struct)

Represents a listener which receives "ctrl-close" notifications sent to the process
via `SetConsoleCtrlHandler`.

A notification to this process notifies *all* listeners listening for
this event. Moreover, the notifications **are coalesced** if they aren't processed
quickly enough. This means that if two notifications are received back-to-back,
then the listener may only receive one item about the two notifications.

## tokio::signal::windows::CtrlLogoff (struct)

Represents a listener which receives "ctrl-logoff" notifications sent to the process
via `SetConsoleCtrlHandler`.

A notification to this process notifies *all* listeners listening for
this event. Moreover, the notifications **are coalesced** if they aren't processed
quickly enough. This means that if two notifications are received back-to-back,
then the listener may only receive one item about the two notifications.

## tokio::signal::windows::CtrlShutdown (struct)

Represents a listener which receives "ctrl-shutdown" notifications sent to the process
via `SetConsoleCtrlHandler`.

A notification to this process notifies *all* listeners listening for
this event. Moreover, the notifications **are coalesced** if they aren't processed
quickly enough. This means that if two notifications are received back-to-back,
then the listener may only receive one item about the two notifications.

## tokio::signal::windows::ctrl_break (function)

Creates a new listener which receives "ctrl-break" notifications sent to the
process.

### tokio::signal::windows::ctrl_break (function) › Examples

```rust,no_run
use tokio::signal::windows::ctrl_break;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // A listener of CTRL-BREAK events.
    let mut signal = ctrl_break()?;

    // Print whenever a CTRL-BREAK event is received.
    loop {
        signal.recv().await;
        println!("got signal CTRL-BREAK");
    }
}
```

## tokio::signal::windows::ctrl_c (function)

Creates a new listener which receives "ctrl-c" notifications sent to the
process.

### tokio::signal::windows::ctrl_c (function) › Examples

```rust,no_run
use tokio::signal::windows::ctrl_c;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // A listener of CTRL-C events.
    let mut signal = ctrl_c()?;

    // Print whenever a CTRL-C event is received.
    for countdown in (0..3).rev() {
        signal.recv().await;
        println!("got CTRL-C. {} more to exit", countdown);
    }

    Ok(())
}
```

## tokio::signal::windows::ctrl_close (function)

Creates a new listener which receives "ctrl-close" notifications sent to the
process.

### tokio::signal::windows::ctrl_close (function) › Examples

```rust,no_run
use tokio::signal::windows::ctrl_close;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // A listener of CTRL-CLOSE events.
    let mut signal = ctrl_close()?;

    // Print whenever a CTRL-CLOSE event is received.
    for countdown in (0..3).rev() {
        signal.recv().await;
        println!("got CTRL-CLOSE. {} more to exit", countdown);
    }

    Ok(())
}
```

## tokio::signal::windows::ctrl_logoff (function)

Creates a new listener which receives "ctrl-logoff" notifications sent to the
process.

### tokio::signal::windows::ctrl_logoff (function) › Examples

```rust,no_run
use tokio::signal::windows::ctrl_logoff;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // A listener of CTRL-LOGOFF events.
    let mut signal = ctrl_logoff()?;

    signal.recv().await;
    println!("got CTRL-LOGOFF. Cleaning up before exiting");

    Ok(())
}
```

## tokio::signal::windows::ctrl_shutdown (function)

Creates a new listener which receives "ctrl-shutdown" notifications sent to the
process.

### tokio::signal::windows::ctrl_shutdown (function) › Examples

```rust,no_run
use tokio::signal::windows::ctrl_shutdown;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // A listener of CTRL-SHUTDOWN events.
    let mut signal = ctrl_shutdown()?;

    signal.recv().await;
    println!("got CTRL-SHUTDOWN. Cleaning up before exiting");

    Ok(())
}
```

## tokio::spawn (function)

Executes the command as a child process, returning a handle to it.

By default, stdin, stdout and stderr are inherited from the parent.

This method will spawn the child process synchronously and return a
handle to a future-aware child process. The `Child` returned implements
`Future` itself to acquire the `ExitStatus` of the child, and otherwise
the `Child` has methods to acquire handles to the stdin, stdout, and
stderr streams.

All I/O this child does will be associated with the current default
event loop.

### tokio::spawn (function) › Examples

Basic usage:

```no_run
use tokio::process::Command;

async fn run_ls() -> std::process::ExitStatus {
    Command::new("ls")
        .spawn()
        .expect("ls command failed to start")
        .wait()
        .await
        .expect("ls command failed to run")
}
```

### tokio::spawn (function) › Caveats

### tokio::spawn (function) › Dropping/Cancellation

Similar to the behavior to the standard library, and unlike the futures
paradigm of dropping-implies-cancellation, a spawned process will, by
default, continue to execute even after the `Child` handle has been dropped.

The [`Command::kill_on_drop`] method can be used to modify this behavior
and kill the child process if the `Child` wrapper is dropped before it
has exited.

### tokio::spawn (function) › Unix Processes

On Unix platforms processes must be "reaped" by their parent process after
they have exited in order to release all OS resources. A child process which
has exited, but has not yet been reaped by its parent is considered a "zombie"
process. Such processes continue to count against limits imposed by the system,
and having too many zombie processes present can prevent additional processes
from being spawned.

The tokio runtime will, on a best-effort basis, attempt to reap and clean up
any process which it has spawned. No additional guarantees are made with regard to
how quickly or how often this procedure will take place.

It is recommended to avoid dropping a [`Child`] process handle before it has been
fully `await`ed if stricter cleanup guarantees are required.

[`Command`]: crate::process::Command
[`Command::kill_on_drop`]: crate::process::Command::kill_on_drop
[`Child`]: crate::process::Child

### tokio::spawn (function) › Errors

On Unix platforms this method will fail with `std::io::ErrorKind::WouldBlock`
if the system process limit is reached (which includes other applications
running on the system).

## tokio::spawn (function)

Spawn the provided task on the `JoinSet`, returning an [`AbortHandle`]
that can be used to remotely cancel the task.

The provided future will start running in the background immediately
when this method is called, even if you don't await anything on this
`JoinSet`.

### tokio::spawn (function) › Panics

This method panics if called outside of a Tokio runtime.

[`AbortHandle`]: crate::task::AbortHandle

## tokio::spawn (function)

Spawn the provided task with this builder's settings and store it in the
[`JoinSet`], returning an [`AbortHandle`] that can be used to remotely
cancel the task.

### tokio::spawn (function) › Returns

An [`AbortHandle`] that can be used to remotely cancel the task.

### tokio::spawn (function) › Panics

This method panics if called outside of a Tokio runtime.

[`AbortHandle`]: crate::task::AbortHandle

## tokio::spawn (function)

Spawns a future onto the Tokio runtime.

This spawns the given future onto the runtime's executor, usually a
thread pool. The thread pool is then responsible for polling the future
until it completes.

The provided future will start running in the background immediately
when `spawn` is called, even if you don't await the returned
`JoinHandle` (assuming that the runtime [is running][running-runtime]).

See [module level][mod] documentation for more details.

[mod]: index.html
[running-runtime]: index.html#driving-the-runtime

### tokio::spawn (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime::Runtime;

# fn dox() {
// Create the runtime
let rt = Runtime::new().unwrap();

// Spawn a future onto the runtime
rt.spawn(async {
    println!("now running on a worker thread");
});
# }
# }
```

## tokio::spawn (function)

Spawns a future onto the Tokio runtime.

This spawns the given future onto the runtime's executor, usually a
thread pool. The thread pool is then responsible for polling the future
until it completes.

The provided future will start running in the background immediately
when `spawn` is called, even if you don't await the returned
`JoinHandle` (assuming that the runtime [is running][running-runtime]).

See [module level][mod] documentation for more details.

[mod]: index.html
[running-runtime]: index.html#driving-the-runtime

### tokio::spawn (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime::Runtime;

# fn dox() {
// Create the runtime
let rt = Runtime::new().unwrap();
// Get a handle from this runtime
let handle = rt.handle();

// Spawn a future onto the runtime using the handle
handle.spawn(async {
    println!("now running on a worker thread");
});
# }
# }
```

## tokio::spawn (function)

Spawns a task with this builder's settings on the current runtime.

### tokio::spawn (function) › Panics

This method panics if called outside of a Tokio runtime.

See [`task::spawn`](crate::task::spawn()) for
more details.

## tokio::spawn_blocking (function)

Runs the provided function on a thread from a dedicated blocking thread pool.

This function _will_ be run on another thread.

See the [documentation in the non-local runtime][Runtime] for more
information.

[Runtime]: crate::runtime::Runtime::spawn_blocking

### tokio::spawn_blocking (function) › Examples

```
use tokio::runtime::LocalRuntime;

# fn dox() {
// Create the runtime
let rt = LocalRuntime::new().unwrap();

// Spawn a blocking function onto the runtime
rt.spawn_blocking(|| {
    println!("now running on a worker thread");
});
# }
```

## tokio::spawn_blocking (function)

Runs the provided function on an executor dedicated to blocking
operations.

### tokio::spawn_blocking (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime::Runtime;

# fn dox() {
// Create the runtime
let rt = Runtime::new().unwrap();
// Get a handle from this runtime
let handle = rt.handle();

// Spawn a blocking function onto the runtime using the handle
handle.spawn_blocking(|| {
    println!("now running on a worker thread");
});
# }
# }
```

## tokio::spawn_blocking (function)

Runs the provided function on an executor dedicated to blocking operations.

### tokio::spawn_blocking (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime::Runtime;

# fn dox() {
// Create the runtime
let rt = Runtime::new().unwrap();

// Spawn a blocking function onto the runtime
rt.spawn_blocking(|| {
    println!("now running on a worker thread");
});
# }
# }
```

## tokio::spawn_blocking (function)

Spawn the blocking code on the blocking threadpool and store
it in this `JoinSet`, returning an [`AbortHandle`] that can be
used to remotely cancel the task.

### tokio::spawn_blocking (function) › Examples

Spawn multiple blocking tasks and wait for them.

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::task::JoinSet;

#[tokio::main]
async fn main() {
    let mut set = JoinSet::new();

    for i in 0..10 {
        set.spawn_blocking(move || { i });
    }

    let mut seen = [false; 10];
    while let Some(res) = set.join_next().await {
        let idx = res.unwrap();
        seen[idx] = true;
    }

    for i in 0..10 {
        assert!(seen[i]);
    }
}
# }
```

### tokio::spawn_blocking (function) › Panics

This method panics if called outside of a Tokio runtime.

[`AbortHandle`]: crate::task::AbortHandle

## tokio::spawn_blocking (function)

Spawn the blocking code on the blocking threadpool with this builder's
settings, and store it in the [`JoinSet`].

### tokio::spawn_blocking (function) › Returns

An [`AbortHandle`] that can be used to remotely cancel the task.

### tokio::spawn_blocking (function) › Panics

This method panics if called outside of a Tokio runtime.

[`JoinSet`]: crate::task::JoinSet
[`AbortHandle`]: crate::task::AbortHandle

## tokio::spawn_blocking (function)

Spawns blocking code on the blocking threadpool.

### tokio::spawn_blocking (function) › Panics

This method panics if called outside of a Tokio runtime.

See [`task::spawn_blocking`](crate::task::spawn_blocking)
for more details.

## tokio::spawn_blocking_on (function)

Spawn the blocking code on the blocking threadpool of the
provided runtime and store it in this `JoinSet`, returning an
[`AbortHandle`] that can be used to remotely cancel the task.

[`AbortHandle`]: crate::task::AbortHandle

## tokio::spawn_blocking_on (function)

Spawn the blocking code on the blocking threadpool of the provided
runtime handle with this builder's settings, and store it in the
[`JoinSet`].

### tokio::spawn_blocking_on (function) › Returns

An [`AbortHandle`] that can be used to remotely cancel the task.

[`JoinSet`]: crate::task::JoinSet
[`AbortHandle`]: crate::task::AbortHandle

## tokio::spawn_blocking_on (function)

Spawns blocking code on the provided [runtime handle]'s blocking threadpool.

See [`Handle::spawn_blocking`] for more details.

[runtime handle]: crate::runtime::Handle
[`Handle::spawn_blocking`]: crate::runtime::Handle::spawn_blocking

## tokio::spawn_local (function)

Spawn the provided task on the current [`LocalSet`] or [`LocalRuntime`]
and store it in this `JoinSet`, returning an [`AbortHandle`] that can
be used to remotely cancel the task.

The provided future will start running in the background immediately
when this method is called, even if you don't await anything on this
`JoinSet`.

### tokio::spawn_local (function) › Panics

This method panics if it is called outside of a `LocalSet` or `LocalRuntime`.

[`LocalSet`]: crate::task::LocalSet
[`LocalRuntime`]: crate::runtime::LocalRuntime
[`AbortHandle`]: crate::task::AbortHandle

## tokio::spawn_local (function)

Spawn the provided task on the current [`LocalSet`] or [`LocalRuntime`]
with this builder's settings, and store it in the [`JoinSet`].

### tokio::spawn_local (function) › Returns

An [`AbortHandle`] that can be used to remotely cancel the task.

### tokio::spawn_local (function) › Panics

This method panics if it is called outside of a `LocalSet` or `LocalRuntime`.

[`LocalSet`]: crate::task::LocalSet
[`LocalRuntime`]: crate::runtime::LocalRuntime
[`AbortHandle`]: crate::task::AbortHandle

## tokio::spawn_local (function)

Spawns a `!Send` task on the current [`LocalSet`] or [`LocalRuntime`] with
this builder's settings.

The spawned future will be run on the same thread that called `spawn_local`.
This may only be called from the context of a [local task set][`LocalSet`]
or a [`LocalRuntime`].

### tokio::spawn_local (function) › Panics

This function panics if called outside of a [local task set][`LocalSet`]
or a [`LocalRuntime`].

See [`task::spawn_local`] for more details.

[`task::spawn_local`]: crate::task::spawn_local
[`LocalSet`]: crate::task::LocalSet
[`LocalRuntime`]: crate::runtime::LocalRuntime

## tokio::spawn_local (function)

Spawns a `!Send` task onto the local task set.

This task is guaranteed to be run on the current thread.

Unlike the free function [`spawn_local`], this method may be used to
spawn local tasks when the `LocalSet` is _not_ running. The provided
future will start running once the `LocalSet` is next started, even if
you don't await the returned `JoinHandle`.

### tokio::spawn_local (function) › Examples

```rust
use tokio::task;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let local = task::LocalSet::new();

// Spawn a future on the local set. This future will be run when
// we call `run_until` to drive the task set.
local.spawn_local(async {
    // ...
});

// Run the local task set.
local.run_until(async move {
    // ...
}).await;

// When `run` finishes, we can spawn _more_ futures, which will
// run in subsequent calls to `run_until`.
local.spawn_local(async {
    // ...
});

local.run_until(async move {
    // ...
}).await;
# }
```
[`spawn_local`]: fn@spawn_local

## tokio::spawn_local (function)

Spawns a task on the runtime.

This is analogous to the [`spawn`] method on the standard [`Runtime`], but works even if the task is not thread-safe.

[`spawn`]: crate::runtime::Runtime::spawn
[`Runtime`]: crate::runtime::Runtime

### tokio::spawn_local (function) › Examples

```
use tokio::runtime::LocalRuntime;

# fn dox() {
// Create the runtime
let rt = LocalRuntime::new().unwrap();

// Spawn a future onto the runtime
rt.spawn_local(async {
    println!("now running on a worker thread");
});
# }
```

## tokio::spawn_local_on (function)

Spawn the provided task on the provided [`LocalSet`] and store it in
this `JoinSet`, returning an [`AbortHandle`] that can be used to
remotely cancel the task.

Unlike the [`spawn_local`] method, this method may be used to spawn local
tasks on a `LocalSet` that is _not_ currently running. The provided
future will start running whenever the `LocalSet` is next started.

[`LocalSet`]: crate::task::LocalSet
[`AbortHandle`]: crate::task::AbortHandle
[`spawn_local`]: Self::spawn_local

## tokio::spawn_local_on (function)

Spawn the provided task on the provided [`LocalSet`] with this builder's
settings, and store it in the [`JoinSet`].

### tokio::spawn_local_on (function) › Returns

An [`AbortHandle`] that can be used to remotely cancel the task.

[`LocalSet`]: crate::task::LocalSet
[`AbortHandle`]: crate::task::AbortHandle

## tokio::spawn_local_on (function)

Spawns `!Send` a task on the provided [`LocalSet`] with this builder's
settings.

See [`LocalSet::spawn_local`] for more details.

[`LocalSet::spawn_local`]: crate::task::LocalSet::spawn_local
[`LocalSet`]: crate::task::LocalSet

## tokio::spawn_on (function)

Spawn a task with this builder's settings on the provided [runtime
handle].

See [`Handle::spawn`] for more details.

[runtime handle]: crate::runtime::Handle
[`Handle::spawn`]: crate::runtime::Handle::spawn

## tokio::spawn_on (function)

Spawn the provided task on the provided [runtime handle] with this
builder's settings, and store it in the [`JoinSet`].

### tokio::spawn_on (function) › Returns

An [`AbortHandle`] that can be used to remotely cancel the task.


[`AbortHandle`]: crate::task::AbortHandle
[runtime handle]: crate::runtime::Handle

## tokio::spawn_on (function)

Spawn the provided task on the provided runtime and store it in this
`JoinSet` returning an [`AbortHandle`] that can be used to remotely
cancel the task.

The provided future will start running in the background immediately
when this method is called, even if you don't await anything on this
`JoinSet`.

[`AbortHandle`]: crate::task::AbortHandle

## tokio::spawn_with (function)

Executes the command as a child process with a custom spawning function,
returning a handle to it.

This is identical to [`Self::spawn`] in every aspect except the spawn:
here, it is customizable through the `with` parameter instead of
defaulting to the usual spawn. In fact, [`Self::spawn`] is just
[`Self::spawn_with`] with [`StdCommand::spawn`].

This is useful mostly under Windows for now, since the platform exposes
special APIs to configure child processes when spawning them with various
attributes that customize the exact behavior of the spawn operation.

### tokio::spawn_with (function) › Examples

Basic usage:

```no_run
# async fn test() { // allow using await
use std::process::Stdio;

let output = tokio::process::Command::new("ls")
    .stdin(Stdio::null())
    .stdout(Stdio::piped())
    .stderr(Stdio::piped())
    .spawn_with(std::process::Command::spawn)
    .unwrap()
    .wait_with_output()
    .await
    .unwrap();
# }
```

Actually customizing the spawn under Windows:

```ignore
#![feature(windows_process_extensions_raw_attribute)]
# #[cfg(windows)]   // Windows-only nightly APIs are used here.
# async fn test() { // Allow using await.
use std::os::windows::process::{CommandExt, ProcThreadAttributeList};
use std::process::Stdio;
use tokio::process::Command;

let parent = Command::new("cmd").spawn().unwrap();
let parent_process_handle = parent.raw_handle();

const PROC_THREAD_ATTRIBUTE_PARENT_PROCESS: usize = 0x00020000;
let attribute_list = ProcThreadAttributeList::build()
    .attribute(PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, &parent_process_handle)
    .finish()
    .unwrap();

let _output = Command::new("ls")
    .stdin(Stdio::null())
    .stdout(Stdio::piped())
    .stderr(Stdio::piped())
    .spawn_with(|cmd| cmd.spawn_with_attributes(&attribute_list))
    .unwrap()
    .wait_with_output()
    .await
    .unwrap();
# }
```

## tokio::spawned_at (function)

Return the source code location where the task was spawned.

## tokio::spawned_tasks_count (function)

Returns the number of tasks spawned in this runtime since it was created.

This count starts at zero when the runtime is created and increases by one each time a task is spawned.

The counter is monotonically increasing. It is never decremented or
reset to zero.

### tokio::spawned_tasks_count (function) › Examples

```
use tokio::runtime::Handle;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let metrics = Handle::current().metrics();

let n = metrics.spawned_tasks_count();
println!("Runtime has had {} tasks spawned", n);
# }
```

## tokio::split (function)

Returns a stream of the contents of this reader split on the byte
`byte`.

This method is the asynchronous equivalent to
[`BufRead::split`](std::io::BufRead::split).

The stream returned from this function will yield instances of
[`io::Result`]`<`[`Option`]`<`[`Vec<u8>`]`>>`. Each vector returned will *not* have
the delimiter byte at the end.

[`io::Result`]: std::io::Result
[`Option`]: core::option::Option
[`Vec<u8>`]: std::vec::Vec

### tokio::split (function) › Errors

Each item of the stream has the same error semantics as
[`AsyncBufReadExt::read_until`](AsyncBufReadExt::read_until).

### tokio::split (function) › Examples

```
# use tokio::io::AsyncBufRead;
use tokio::io::AsyncBufReadExt;

# async fn dox(my_buf_read: impl AsyncBufRead + Unpin) -> std::io::Result<()> {
let mut segments = my_buf_read.split(b'f');

while let Some(segment) = segments.next_segment().await? {
    println!("length = {}", segment.len())
}
# Ok(())
# }
```

## tokio::split (function)

Splits `n` permits from `self` and returns a new [`OwnedSemaphorePermit`] instance that holds `n` permits.

If there are insufficient permits and it's not possible to reduce by `n`, returns `None`.

### tokio::split (function) › Note

It will clone the owned `Arc<Semaphore>` to construct the new instance.

### tokio::split (function) › Examples

```
use std::sync::Arc;
use tokio::sync::Semaphore;

let sem = Arc::new(Semaphore::new(3));

let mut p1 = sem.try_acquire_many_owned(3).unwrap();
let p2 = p1.split(1).unwrap();

assert_eq!(p1.num_permits(), 2);
assert_eq!(p2.num_permits(), 1);
```

## tokio::split (function)

Splits `n` permits from `self` and returns a new [`SemaphorePermit`] instance that holds `n` permits.

If there are insufficient permits and it's not possible to reduce by `n`, returns `None`.

### tokio::split (function) › Examples

```
use std::sync::Arc;
use tokio::sync::Semaphore;

let sem = Arc::new(Semaphore::new(3));

let mut p1 = sem.try_acquire_many(3).unwrap();
let p2 = p1.split(1).unwrap();

assert_eq!(p1.num_permits(), 2);
assert_eq!(p2.num_permits(), 1);
```

## tokio::split (function)

Splits a `TcpStream` into a read half and a write half, which can be used
to read and write the stream concurrently.

This method is more efficient than [`into_split`], but the halves cannot be
moved into independently spawned tasks.

[`into_split`]: TcpStream::into_split()

## tokio::split (function)

Splits a `UnixStream` into a read half and a write half, which can be used
to read and write the stream concurrently.

This method is more efficient than [`into_split`], but the halves cannot be
moved into independently spawned tasks.

[`into_split`]: Self::into_split()

## tokio::start_kill (function)

Attempts to force the child to exit, but does not wait for the request
to take effect.

On Unix platforms, this is the equivalent to sending a `SIGKILL`. Note
that on Unix platforms it is possible for a zombie process to remain
after a kill is sent; to avoid this, the caller should ensure that either
`child.wait().await` or `child.try_wait()` is invoked successfully.

## tokio::start_paused (function)

Controls if the runtime's clock starts paused or advancing.

Pausing time requires the current-thread runtime; construction of
the runtime will panic otherwise.

### tokio::start_paused (function) › Examples

```
use tokio::runtime;

let rt = runtime::Builder::new_current_thread()
    .enable_time()
    .start_paused(true)
    .build()
    .unwrap();
```

## tokio::start_seek (function)

Attempts to seek to an offset, in bytes, in a stream.

A seek beyond the end of a stream is allowed, but behavior is defined
by the implementation.

If this function returns successfully, then the job has been submitted.
To find out when it completes, call `poll_complete`.

### tokio::start_seek (function) › Errors

This function can return [`io::ErrorKind::Other`] in case there is
another seek in progress. To avoid this, it is advisable that any call
to `start_seek` is preceded by a call to `poll_complete` to ensure all
pending seeks have completed.

## tokio::status (function)

Executes the command as a child process, waiting for it to finish and
collecting its exit status.

By default, stdin, stdout and stderr are inherited from the parent.
If any input/output handles are set to a pipe then they will be immediately
closed after the child is spawned.

All I/O this child does will be associated with the current default
event loop.

The destructor of the future returned by this function will kill
the child if [`kill_on_drop`] is set to true.

[`kill_on_drop`]: fn@Self::kill_on_drop

### tokio::status (function) › Errors

This future will return an error if the child process cannot be spawned
or if there is an error while awaiting its status.

On Unix platforms this method will fail with `std::io::ErrorKind::WouldBlock`
if the system process limit is reached (which includes other applications
running on the system).

### tokio::status (function) › Examples

Basic usage:

```no_run
use tokio::process::Command;

async fn run_ls() -> std::process::ExitStatus {
    Command::new("ls")
        .status()
        .await
        .expect("ls command failed to run")
}
```

## tokio::stderr (function)

Sets configuration for the child process's standard error (stderr) handle.

Defaults to [`inherit`] when used with `spawn` or `status`, and
defaults to [`piped`] when used with `output`.

[`inherit`]: std::process::Stdio::inherit
[`piped`]: std::process::Stdio::piped

### tokio::stderr (function) › Examples

Basic usage:

```no_run
# async fn test() { // allow using await
use tokio::process::Command;
use std::process::{Stdio};

let output = Command::new("ls")
        .stderr(Stdio::null())
        .output().await.unwrap();
# }
```

## tokio::stderr (struct_field)

The handle for reading from the child's standard error (stderr), if it
has been captured. You might find it helpful to do

```no_run
# let mut child = tokio::process::Command::new("echo").spawn().unwrap();
let stderr = child.stderr.take().unwrap();
```

to avoid partially moving the `child` and thus blocking yourself from calling
functions on `child` while using `stderr`.

## tokio::stdin (function)

Sets configuration for the child process's standard input (stdin) handle.

Defaults to [`inherit`].

[`inherit`]: std::process::Stdio::inherit

### tokio::stdin (function) › Examples

Basic usage:

```no_run
# async fn test() { // allow using await
use std::process::{Stdio};
use tokio::process::Command;

let output = Command::new("ls")
        .stdin(Stdio::null())
        .output().await.unwrap();
# }
```

## tokio::stdin (struct_field)

The handle for writing to the child's standard input (stdin), if it has
been captured. To avoid partially moving the `child` and thus blocking
yourself from calling functions on `child` while using `stdin`, you might
find it helpful to do:

```no_run
# let mut child = tokio::process::Command::new("echo").spawn().unwrap();
let stdin = child.stdin.take().unwrap();
```

## tokio::stdout (function)

Sets configuration for the child process's standard output (stdout) handle.

Defaults to [`inherit`] when used with `spawn` or `status`, and
defaults to [`piped`] when used with `output`.

[`inherit`]: std::process::Stdio::inherit
[`piped`]: std::process::Stdio::piped

### tokio::stdout (function) › Examples

Basic usage:

```no_run
# async fn test() { // allow using await
use tokio::process::Command;
use std::process::Stdio;

let output = Command::new("ls")
        .stdout(Stdio::null())
        .output().await.unwrap();
# }
```

## tokio::stdout (struct_field)

The handle for reading from the child's standard output (stdout), if it
has been captured. You might find it helpful to do

```no_run
# let mut child = tokio::process::Command::new("echo").spawn().unwrap();
let stdout = child.stdout.take().unwrap();
```

to avoid partially moving the `child` and thus blocking yourself from calling
functions on `child` while using `stdout`.

## tokio::stream_position (function)

Creates a future which will return the current seek position from the
start of the stream.

This is equivalent to `self.seek(SeekFrom::Current(0))`.

## tokio::strong_count (function)

Returns the number of [`Sender`] handles.

## tokio::strong_count (function)

Returns the number of [`Sender`] handles.

## tokio::strong_count (function)

Returns the number of [`Sender`] handles.

## tokio::strong_count (function)

Returns the number of [`Sender`] handles.

## tokio::strong_count (function)

Returns the number of [`UnboundedSender`] handles.

## tokio::strong_count (function)

Returns the number of [`UnboundedSender`] handles.

## tokio::subscribe (function)

Creates a new [`Receiver`] connected to this `Sender`.

All messages sent before this call to `subscribe` are initially marked
as seen by the new `Receiver`.

This method can be called even if there are no other receivers. In this
case, the channel is reopened.

### tokio::subscribe (function) › Examples

The new channel will receive messages sent on this `Sender`.

```
use tokio::sync::watch;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, _rx) = watch::channel(0u64);

tx.send(5).unwrap();

let rx = tx.subscribe();
assert_eq!(5, *rx.borrow());

tx.send(10).unwrap();
assert_eq!(10, *rx.borrow());
# }
```

The most recent message is considered seen by the channel, so this test
is guaranteed to pass.

```
use tokio::sync::watch;
use tokio::time::Duration;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, _rx) = watch::channel(0u64);
tx.send(5).unwrap();
let mut rx = tx.subscribe();

tokio::spawn(async move {
    // by spawning and sleeping, the message is sent after `main`
    // hits the call to `changed`.
    # if false {
    tokio::time::sleep(Duration::from_millis(10)).await;
    # }
    tx.send(100).unwrap();
});

rx.changed().await.unwrap();
assert_eq!(100, *rx.borrow());
# }
```

## tokio::subscribe (function)

Creates a new [`Receiver`] handle that will receive values sent **after**
this call to `subscribe`.

### tokio::subscribe (function) › Examples

```
use tokio::sync::broadcast;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, _rx) = broadcast::channel(16);

// Will not be seen
tx.send(10).unwrap();

let mut rx = tx.subscribe();

tx.send(20).unwrap();

let value = rx.recv().await.unwrap();
assert_eq!(20, value);
# }
```

## tokio::symbol_address (function)

Returns the starting symbol address of the frame of this function.

## tokio::symbols (function)

Return an iterator over the symbols of this backtrace frame.

Due to inlining, it is possible for there to be multiple [`BacktraceSymbol`] items relating
to a single frame. The first symbol listed is the "innermost function",
whereas the last symbol is the outermost (last caller).

## tokio::sync::barrier::Barrier (struct)

A barrier enables multiple tasks to synchronize the beginning of some computation.

```
# #[tokio::main(flavor = "current_thread")]
# async fn main() {
use tokio::sync::Barrier;
use std::sync::Arc;

let mut handles = Vec::with_capacity(10);
let barrier = Arc::new(Barrier::new(10));
for _ in 0..10 {
    let c = barrier.clone();
    // The same messages will be printed together.
    // You will NOT see any interleaving.
    handles.push(tokio::spawn(async move {
        println!("before wait");
        let wait_result = c.wait().await;
        println!("after wait");
        wait_result
    }));
}

// Will not resolve until all "after wait" messages have been printed
let mut num_leaders = 0;
for handle in handles {
    let wait_result = handle.await.unwrap();
    if wait_result.is_leader() {
        num_leaders += 1;
    }
}

// Exactly one barrier will resolve as the "leader"
assert_eq!(num_leaders, 1);
# }
```

## tokio::sync::barrier::BarrierWaitResult (struct)

A `BarrierWaitResult` is returned by `wait` when all tasks in the `Barrier` have rendezvoused.

## tokio::sync::batch_semaphore::AcquireError (struct)

Error returned from the [`Semaphore::acquire`] function.

An `acquire` operation can only fail if the semaphore has been
[closed].

[closed]: crate::sync::Semaphore::close
[`Semaphore::acquire`]: crate::sync::Semaphore::acquire

## tokio::sync::batch_semaphore::TryAcquireError (enum)

Error returned from the [`Semaphore::try_acquire`] function.

[`Semaphore::try_acquire`]: crate::sync::Semaphore::try_acquire

## tokio::sync::batch_semaphore::TryAcquireError::Closed (variant)

The semaphore has been [closed] and cannot issue new permits.

[closed]: crate::sync::Semaphore::close

## tokio::sync::batch_semaphore::TryAcquireError::NoPermits (variant)

The semaphore has no available permits.

## tokio::sync::broadcast::Receiver (struct)

Receiving-half of the [`broadcast`] channel.

Must not be used concurrently. Messages may be retrieved using
[`recv`][Receiver::recv].

To turn this receiver into a `Stream`, you can use the [`BroadcastStream`]
wrapper.

[`BroadcastStream`]: https://docs.rs/tokio-stream/0.1/tokio_stream/wrappers/struct.BroadcastStream.html

### tokio::sync::broadcast::Receiver (struct) › Examples

```
use tokio::sync::broadcast;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx1) = broadcast::channel(16);
let mut rx2 = tx.subscribe();

tokio::spawn(async move {
    assert_eq!(rx1.recv().await.unwrap(), 10);
    assert_eq!(rx1.recv().await.unwrap(), 20);
});

tokio::spawn(async move {
    assert_eq!(rx2.recv().await.unwrap(), 10);
    assert_eq!(rx2.recv().await.unwrap(), 20);
});

tx.send(10).unwrap();
tx.send(20).unwrap();
# }
```

[`broadcast`]: crate::sync::broadcast

## tokio::sync::broadcast::Sender (struct)

Sending-half of the [`broadcast`] channel.

May be used from many threads. Messages can be sent with
[`send`][Sender::send].

### tokio::sync::broadcast::Sender (struct) › Examples

```
use tokio::sync::broadcast;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx1) = broadcast::channel(16);
let mut rx2 = tx.subscribe();

tokio::spawn(async move {
    assert_eq!(rx1.recv().await.unwrap(), 10);
    assert_eq!(rx1.recv().await.unwrap(), 20);
});

tokio::spawn(async move {
    assert_eq!(rx2.recv().await.unwrap(), 10);
    assert_eq!(rx2.recv().await.unwrap(), 20);
});

tx.send(10).unwrap();
tx.send(20).unwrap();
# }
```

[`broadcast`]: crate::sync::broadcast

## tokio::sync::broadcast::WeakSender (struct)

A sender that does not prevent the channel from being closed.

If all [`Sender`] instances of a channel were dropped and only `WeakSender`
instances remain, the channel is closed.

In order to send messages, the `WeakSender` needs to be upgraded using
[`WeakSender::upgrade`], which returns `Option<Sender>`. It returns `None`
if all `Sender`s have been dropped, and otherwise it returns a `Sender`.

[`Sender`]: Sender
[`WeakSender::upgrade`]: WeakSender::upgrade

### tokio::sync::broadcast::WeakSender (struct) › Examples

```
use tokio::sync::broadcast::channel;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, _rx) = channel::<i32>(15);
let tx_weak = tx.downgrade();

// Upgrading will succeed because `tx` still exists.
assert!(tx_weak.upgrade().is_some());

// If we drop `tx`, then it will fail.
drop(tx);
assert!(tx_weak.clone().upgrade().is_none());
# }
```

## tokio::sync::broadcast::channel (function)

Create a bounded, multi-producer, multi-consumer channel where each sent
value is broadcasted to all active receivers.

**Note:** The provided `capacity` is rounded **up** to the next power of
two. That rounded size is the number of messages the internal ring buffer
can retain, and is what [lag detection](self#lagging) uses. For example,
`channel(3)` behaves as if the capacity were 4.

All data sent on [`Sender`] will become available on every active
[`Receiver`] in the same order as it was sent.

The `Sender` can be cloned to `send` to the same channel from multiple
points in the process or it can be used concurrently from an `Arc`. New
`Receiver` handles are created by calling [`Sender::subscribe`].

If all [`Receiver`] handles are dropped, the `send` method will return a
[`SendError`]. Similarly, if all [`Sender`] handles are dropped, the [`recv`]
method will return a [`RecvError`].

[`Sender`]: crate::sync::broadcast::Sender
[`Sender::subscribe`]: crate::sync::broadcast::Sender::subscribe
[`Receiver`]: crate::sync::broadcast::Receiver
[`recv`]: crate::sync::broadcast::Receiver::recv
[`SendError`]: crate::sync::broadcast::error::SendError
[`RecvError`]: crate::sync::broadcast::error::RecvError

### tokio::sync::broadcast::channel (function) › Examples

```
use tokio::sync::broadcast;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx1) = broadcast::channel(16);
let mut rx2 = tx.subscribe();

tokio::spawn(async move {
    assert_eq!(rx1.recv().await.unwrap(), 10);
    assert_eq!(rx1.recv().await.unwrap(), 20);
});

tokio::spawn(async move {
    assert_eq!(rx2.recv().await.unwrap(), 10);
    assert_eq!(rx2.recv().await.unwrap(), 20);
});

tx.send(10).unwrap();
tx.send(20).unwrap();
# }
```

### tokio::sync::broadcast::channel (function) › Panics

This will panic if `capacity` is equal to `0`.

This pre-allocates space for `capacity` messages. Allocation failure may result in a panic or
[an allocation error](std::alloc::handle_alloc_error).

## tokio::sync::broadcast::error::RecvError (enum)

An error returned from the [`recv`] function on a [`Receiver`].

[`recv`]: crate::sync::broadcast::Receiver::recv
[`Receiver`]: crate::sync::broadcast::Receiver

## tokio::sync::broadcast::error::RecvError::Closed (variant)

There are no more active senders implying no further messages will ever
be sent.

## tokio::sync::broadcast::error::RecvError::Lagged (variant)

The receiver lagged too far behind: one or more messages were
overwritten in the ring buffer before this receiver could read them.

The receiver remains subscribed. Its internal cursor has been advanced
to the oldest message still retained by the channel; the next
successful [`recv`] call returns that message (unless further sends
overwrite it first).

The `u64` is the number of messages that were skipped (dropped before
the receiver's previous cursor position).

[`recv`]: crate::sync::broadcast::Receiver::recv

## tokio::sync::broadcast::error::SendError (struct)

Error returned by the [`send`] function on a [`Sender`].

A **send** operation can only fail if there are no active receivers,
implying that the message could never be received. The error contains the
message being sent as a payload so it can be recovered.

[`send`]: crate::sync::broadcast::Sender::send
[`Sender`]: crate::sync::broadcast::Sender

## tokio::sync::broadcast::error::TryRecvError (enum)

An error returned from the [`try_recv`] function on a [`Receiver`].

[`try_recv`]: crate::sync::broadcast::Receiver::try_recv
[`Receiver`]: crate::sync::broadcast::Receiver

## tokio::sync::broadcast::error::TryRecvError::Closed (variant)

There are no more active senders implying no further messages will ever
be sent.

## tokio::sync::broadcast::error::TryRecvError::Empty (variant)

The channel is currently empty. There are still active
[`Sender`] handles, so data may yet become available.

[`Sender`]: crate::sync::broadcast::Sender

## tokio::sync::broadcast::error::TryRecvError::Lagged (variant)

The receiver lagged too far behind: one or more messages were
overwritten in the ring buffer before this receiver could read them.

The receiver remains subscribed. Its internal cursor has been advanced
to the oldest message still retained by the channel; the next
successful [`try_recv`] call returns that message (unless further sends
overwrite it first).

The `u64` is the number of messages that were skipped (dropped before
the receiver's previous cursor position).

[`try_recv`]: crate::sync::broadcast::Receiver::try_recv

## tokio::sync::mpsc::bounded::OwnedPermit (struct)

Owned permit to send one value into the channel.

This is identical to the [`Permit`] type, except that it moves the sender
rather than borrowing it.

`OwnedPermit` values are returned by [`Sender::reserve_owned()`] and
[`Sender::try_reserve_owned()`] and are used to guarantee channel capacity
before generating a message to send.

[`Permit`]: Permit
[`Sender::reserve_owned()`]: Sender::reserve_owned
[`Sender::try_reserve_owned()`]: Sender::try_reserve_owned

## tokio::sync::mpsc::bounded::Permit (struct)

Permits to send one value into the channel.

`Permit` values are returned by [`Sender::reserve()`] and [`Sender::try_reserve()`]
and are used to guarantee channel capacity before generating a message to send.

[`Sender::reserve()`]: Sender::reserve
[`Sender::try_reserve()`]: Sender::try_reserve

## tokio::sync::mpsc::bounded::PermitIterator (struct)

An [`Iterator`] of [`Permit`] that can be used to hold `n` slots in the channel.

`PermitIterator` values are returned by [`Sender::reserve_many()`] and [`Sender::try_reserve_many()`]
and are used to guarantee channel capacity before generating `n` messages to send.

[`Sender::reserve_many()`]: Sender::reserve_many
[`Sender::try_reserve_many()`]: Sender::try_reserve_many

## tokio::sync::mpsc::bounded::Receiver (struct)

Receives values from the associated `Sender`.

Instances are created by the [`channel`] function.

This receiver can be turned into a `Stream` using [`ReceiverStream`].

[`ReceiverStream`]: https://docs.rs/tokio-stream/0.1/tokio_stream/wrappers/struct.ReceiverStream.html

## tokio::sync::mpsc::bounded::Sender (struct)

Sends values to the associated `Receiver`.

Instances are created by the [`channel`] function.

To convert the `Sender` into a `Sink` or use it in a poll function, you can
use the [`PollSender`] utility.

[`PollSender`]: https://docs.rs/tokio-util/latest/tokio_util/sync/struct.PollSender.html

## tokio::sync::mpsc::bounded::WeakSender (struct)

A sender that does not prevent the channel from being closed.

If all [`Sender`] instances of a channel were dropped and only `WeakSender`
instances remain, the channel is closed.

In order to send messages, the `WeakSender` needs to be upgraded using
[`WeakSender::upgrade`], which returns `Option<Sender>`. It returns `None`
if all `Sender`s have been dropped, and otherwise it returns a `Sender`.

[`Sender`]: Sender
[`WeakSender::upgrade`]: WeakSender::upgrade

### tokio::sync::mpsc::bounded::WeakSender (struct) › Examples

```
use tokio::sync::mpsc::channel;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, _rx) = channel::<i32>(15);
let tx_weak = tx.downgrade();

// Upgrading will succeed because `tx` still exists.
assert!(tx_weak.upgrade().is_some());

// If we drop `tx`, then it will fail.
drop(tx);
assert!(tx_weak.clone().upgrade().is_none());
# }
```

## tokio::sync::mpsc::bounded::channel (function)

Creates a bounded mpsc channel for communicating between asynchronous tasks
with backpressure.

The channel will buffer up to the provided number of messages.  Once the
buffer is full, attempts to send new messages will wait until a message is
received from the channel. The provided buffer capacity must be at least 1.

All data sent on `Sender` will become available on `Receiver` in the same
order as it was sent.

The `Sender` can be cloned to `send` to the same channel from multiple code
locations. Only one `Receiver` is supported.

If the `Receiver` is disconnected while trying to `send`, the `send` method
will return a `SendError`. Similarly, if `Sender` is disconnected while
trying to `recv`, the `recv` method will return `None`.

### tokio::sync::mpsc::bounded::channel (function) › Panics

Panics if the buffer capacity is 0, or too large. Currently the maximum
capacity is [`Semaphore::MAX_PERMITS`].

[`Semaphore::MAX_PERMITS`]: crate::sync::Semaphore::MAX_PERMITS

### tokio::sync::mpsc::bounded::channel (function) › Examples

```rust
use tokio::sync::mpsc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = mpsc::channel(100);

tokio::spawn(async move {
    for i in 0..10 {
        if let Err(_) = tx.send(i).await {
            println!("receiver dropped");
            return;
        }
    }
});

while let Some(i) = rx.recv().await {
     println!("got = {}", i);
}
# }
```

## tokio::sync::mpsc::error::SendError (struct)

Error returned by [`Sender::send`](super::Sender::send).

## tokio::sync::mpsc::error::SendTimeoutError (enum)

Error returned by [`Sender::send_timeout`](super::Sender::send_timeout).

## tokio::sync::mpsc::error::SendTimeoutError::Closed (variant)

The receive half of the channel was explicitly closed or has been
dropped.

## tokio::sync::mpsc::error::SendTimeoutError::Timeout (variant)

The data could not be sent on the channel because the channel is
full, and the timeout to send has elapsed.

## tokio::sync::mpsc::error::TryRecvError (enum)

Error returned by [`Receiver::try_recv`](super::Receiver::try_recv).

## tokio::sync::mpsc::error::TryRecvError::Disconnected (variant)

The **channel**'s sending half has become disconnected, and there will
never be any more data received on it.

## tokio::sync::mpsc::error::TryRecvError::Empty (variant)

This **channel** is currently empty, but the **Sender**(s) have not yet
disconnected, so data may yet become available.

## tokio::sync::mpsc::error::TrySendError (enum)

Error returned by [`Sender::try_send`](super::Sender::try_send).

## tokio::sync::mpsc::error::TrySendError::Closed (variant)

The receive half of the channel was explicitly closed or has been
dropped.

## tokio::sync::mpsc::error::TrySendError::Full (variant)

The data could not be sent on the channel because the channel is
currently full and sending would require blocking.

## tokio::sync::mpsc::unbounded::UnboundedReceiver (struct)

Receive values from the associated `UnboundedSender`.

Instances are created by the [`unbounded_channel`] function.

This receiver can be turned into a `Stream` using [`UnboundedReceiverStream`].

[`UnboundedReceiverStream`]: https://docs.rs/tokio-stream/0.1/tokio_stream/wrappers/struct.UnboundedReceiverStream.html

## tokio::sync::mpsc::unbounded::UnboundedSender (struct)

Send values to the associated `UnboundedReceiver`.

Instances are created by the [`unbounded_channel`] function.

## tokio::sync::mpsc::unbounded::WeakUnboundedSender (struct)

An unbounded sender that does not prevent the channel from being closed.

If all [`UnboundedSender`] instances of a channel were dropped and only
`WeakUnboundedSender` instances remain, the channel is closed.

In order to send messages, the `WeakUnboundedSender` needs to be upgraded using
[`WeakUnboundedSender::upgrade`], which returns `Option<UnboundedSender>`. It returns `None`
if all `UnboundedSender`s have been dropped, and otherwise it returns an `UnboundedSender`.

[`UnboundedSender`]: UnboundedSender
[`WeakUnboundedSender::upgrade`]: WeakUnboundedSender::upgrade

### tokio::sync::mpsc::unbounded::WeakUnboundedSender (struct) › Examples

```
use tokio::sync::mpsc::unbounded_channel;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, _rx) = unbounded_channel::<i32>();
let tx_weak = tx.downgrade();

// Upgrading will succeed because `tx` still exists.
assert!(tx_weak.upgrade().is_some());

// If we drop `tx`, then it will fail.
drop(tx);
assert!(tx_weak.clone().upgrade().is_none());
# }
```

## tokio::sync::mpsc::unbounded::unbounded_channel (function)

Creates an unbounded mpsc channel for communicating between asynchronous
tasks without backpressure.

A `send` on this channel will always succeed as long as the receive half has
not been closed. If the receiver falls behind, messages will be arbitrarily
buffered.

**Note** that the amount of available system memory is an implicit bound to
the channel. Using an `unbounded` channel has the ability of causing the
process to run out of memory. In this case, the process will be aborted.

## tokio::sync::mutex::MappedMutexGuard (struct)

A handle to a held `Mutex` that has had a function applied to it via [`MutexGuard::map`].

This can be used to hold a subfield of the protected data.

[`MutexGuard::map`]: method@MutexGuard::map

## tokio::sync::mutex::Mutex (struct)

An asynchronous `Mutex`-like type.

This type acts similarly to [`std::sync::Mutex`], with two major
differences: [`lock`] is an async method so does not block, and the lock
guard is designed to be held across `.await` points.

Tokio's Mutex operates on a guaranteed FIFO basis.
This means that the order in which tasks call the [`lock`] method is
the exact order in which they will acquire the lock.

### tokio::sync::mutex::Mutex (struct) › Which kind of mutex should you use?

Contrary to popular belief, it is ok and often preferred to use the ordinary
[`Mutex`][std] from the standard library in asynchronous code.

The feature that the async mutex offers over the blocking mutex is the
ability to keep it locked across an `.await` point. This makes the async
mutex more expensive than the blocking mutex, so the blocking mutex should
be preferred in the cases where it can be used. The primary use case for the
async mutex is to provide shared mutable access to IO resources such as a
database connection. If the value behind the mutex is just data, it's
usually appropriate to use a blocking mutex such as the one in the standard
library or [`parking_lot`].

Note that, although the compiler will not prevent the std `Mutex` from holding
its guard across `.await` points in situations where the task is not movable
between threads, this virtually never leads to correct concurrent code in
practice as it can easily lead to deadlocks.

A common pattern is to wrap the `Arc<Mutex<...>>` in a struct that provides
non-async methods for performing operations on the data within, and only
lock the mutex inside these methods. The [mini-redis] example provides an
illustration of this pattern.

Additionally, when you _do_ want shared access to an IO resource, it is
often better to spawn a task to manage the IO resource, and to use message
passing to communicate with that task.

[std]: std::sync::Mutex
[`parking_lot`]: https://docs.rs/parking_lot
[mini-redis]: https://github.com/tokio-rs/mini-redis/blob/master/src/db.rs

### tokio::sync::mutex::Mutex (struct) › Examples:

```rust,no_run
use tokio::sync::Mutex;
use std::sync::Arc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let data1 = Arc::new(Mutex::new(0));
let data2 = Arc::clone(&data1);

tokio::spawn(async move {
    let mut lock = data2.lock().await;
    *lock += 1;
});

let mut lock = data1.lock().await;
*lock += 1;
# }
```


```rust,no_run
use tokio::sync::Mutex;
use std::sync::Arc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let count = Arc::new(Mutex::new(0));

for i in 0..5 {
    let my_count = Arc::clone(&count);
    tokio::spawn(async move {
        for j in 0..10 {
            let mut lock = my_count.lock().await;
            *lock += 1;
            println!("{} {} {}", i, j, lock);
        }
    });
}

loop {
    if *count.lock().await >= 50 {
        break;
    }
}
println!("Count hit 50.");
# }
```
There are a few things of note here to pay attention to in this example.
1. The mutex is wrapped in an [`Arc`] to allow it to be shared across
   threads.
2. Each spawned task obtains a lock and releases it on every iteration.
3. Mutation of the data protected by the Mutex is done by de-referencing
   the obtained lock as seen on lines 13 and 20.

Tokio's Mutex works in a simple FIFO (first in, first out) style where all
calls to [`lock`] complete in the order they were performed. In that way the
Mutex is "fair" and predictable in how it distributes the locks to inner
data. Locks are released and reacquired after every iteration, so basically,
each thread goes to the back of the line after it increments the value once.
Note that there's some unpredictability to the timing between when the
threads are started, but once they are going they alternate predictably.
Finally, since there is only a single valid lock at any given time, there is
no possibility of a race condition when mutating the inner value.

Note that in contrast to [`std::sync::Mutex`], this implementation does not
poison the mutex when a thread holding the [`MutexGuard`] panics. In such a
case, the mutex will be unlocked. If the panic is caught, this might leave
the data protected by the mutex in an inconsistent state.

[`Mutex`]: struct@Mutex
[`MutexGuard`]: struct@MutexGuard
[`Arc`]: struct@std::sync::Arc
[`std::sync::Mutex`]: struct@std::sync::Mutex
[`Send`]: trait@std::marker::Send
[`lock`]: method@Mutex::lock

## tokio::sync::mutex::MutexGuard (struct)

A handle to a held `Mutex`. The guard can be held across any `.await` point
as it is [`Send`].

As long as you have this guard, you have exclusive access to the underlying
`T`. The guard internally borrows the `Mutex`, so the mutex will not be
dropped while a guard exists.

The lock is automatically released whenever the guard is dropped, at which
point `lock` will succeed yet again.

## tokio::sync::mutex::OwnedMappedMutexGuard (struct)

A owned handle to a held `Mutex` that has had a function applied to it via
[`OwnedMutexGuard::map`].

This can be used to hold a subfield of the protected data.

[`OwnedMutexGuard::map`]: method@OwnedMutexGuard::map

## tokio::sync::mutex::OwnedMutexGuard (struct)

An owned handle to a held `Mutex`.

This guard is only available from a `Mutex` that is wrapped in an [`Arc`]. It
is identical to `MutexGuard`, except that rather than borrowing the `Mutex`,
it clones the `Arc`, incrementing the reference count. This means that
unlike `MutexGuard`, it will have the `'static` lifetime.

As long as you have this guard, you have exclusive access to the underlying
`T`. The guard internally keeps a reference-counted pointer to the original
`Mutex`, so even if the lock goes away, the guard remains valid.

The lock is automatically released whenever the guard is dropped, at which
point `lock` will succeed yet again.

[`Arc`]: std::sync::Arc

## tokio::sync::mutex::TryLockError (struct)

Error returned from the [`Mutex::try_lock`], [`RwLock::try_read`] and
[`RwLock::try_write`] functions.

`Mutex::try_lock` operation will only fail if the mutex is already locked.

`RwLock::try_read` operation will only fail if the lock is currently held
by an exclusive writer.

`RwLock::try_write` operation will only fail if the lock is currently held
by any reader or by an exclusive writer.

[`Mutex::try_lock`]: Mutex::try_lock
[`RwLock::try_read`]: fn@super::RwLock::try_read
[`RwLock::try_write`]: fn@super::RwLock::try_write

## tokio::sync::notify::Notified (struct)

Future returned from [`Notify::notified()`].

This future is fused, so once it has completed, any future calls to poll
will immediately return `Poll::Ready`.

## tokio::sync::notify::Notify (struct)

Notifies a single task to wake up.

`Notify` provides a basic mechanism to notify a single task of an event.
`Notify` itself does not carry any data. Instead, it is to be used to signal
another task to perform an operation.

A `Notify` can be thought of as a [`Semaphore`] starting with 0 permits. The
[`notified().await`] method waits for a permit to become available, and
[`notify_one()`] sets a permit **if there currently are no available
permits**.

The synchronization details of `Notify` are similar to
[`thread::park`][park] and [`Thread::unpark`][unpark] from std. A [`Notify`]
value contains a single permit. [`notified().await`] waits for the permit to
be made available, consumes the permit, and resumes.  [`notify_one()`] sets
the permit, waking a pending task if there is one.

If `notify_one()` is called **before** `notified().await`, then the next
call to `notified().await` will complete immediately, consuming the permit.
Any subsequent calls to `notified().await` will wait for a new permit.

If `notify_one()` is called **multiple** times before `notified().await`,
only a **single** permit is stored. The next call to `notified().await` will
complete immediately, but the one after will wait for a new permit.

### tokio::sync::notify::Notify (struct) › Examples

Basic usage.

```
use tokio::sync::Notify;
use std::sync::Arc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let notify = Arc::new(Notify::new());
let notify2 = notify.clone();

let handle = tokio::spawn(async move {
    notify2.notified().await;
    println!("received notification");
});

println!("sending notification");
notify.notify_one();

// Wait for task to receive notification.
handle.await.unwrap();
# }
```

Unbound multi-producer single-consumer (mpsc) channel.

No wakeups can be lost when using this channel because the call to
`notify_one()` will store a permit in the `Notify`, which the following call
to `notified()` will consume.

```
use tokio::sync::Notify;

use std::collections::VecDeque;
use std::sync::Mutex;

struct Channel<T> {
    values: Mutex<VecDeque<T>>,
    notify: Notify,
}

impl<T> Channel<T> {
    pub fn send(&self, value: T) {
        self.values.lock().unwrap()
            .push_back(value);

        // Notify the consumer a value is available
        self.notify.notify_one();
    }

    // This is a single-consumer channel, so several concurrent calls to
    // `recv` are not allowed.
    pub async fn recv(&self) -> T {
        loop {
            // Drain values
            if let Some(value) = self.values.lock().unwrap().pop_front() {
                return value;
            }

            // Wait for values to be available
            self.notify.notified().await;
        }
    }
}
```

Unbound multi-producer multi-consumer (mpmc) channel.

The call to [`enable`] is important because otherwise if you have two
calls to `recv` and two calls to `send` in parallel, the following could
happen:

 1. Both calls to `try_recv` return `None`.
 2. Both new elements are added to the vector.
 3. The `notify_one` method is called twice, adding only a single
    permit to the `Notify`.
 4. Both calls to `recv` reach the `Notified` future. One of them
    consumes the permit, and the other sleeps forever.

By adding the `Notified` futures to the list by calling `enable` before
`try_recv`, the `notify_one` calls in step three would remove the
futures from the list and mark them notified instead of adding a permit
to the `Notify`. This ensures that both futures are woken.

Notice that this failure can only happen if there are two concurrent calls
to `recv`. This is why the mpsc example above does not require a call to
`enable`.

```
use tokio::sync::Notify;

use std::collections::VecDeque;
use std::sync::Mutex;

struct Channel<T> {
    messages: Mutex<VecDeque<T>>,
    notify_on_sent: Notify,
}

impl<T> Channel<T> {
    pub fn send(&self, msg: T) {
        let mut locked_queue = self.messages.lock().unwrap();
        locked_queue.push_back(msg);
        drop(locked_queue);

        // Send a notification to one of the calls currently
        // waiting in a call to `recv`.
        self.notify_on_sent.notify_one();
    }

    pub fn try_recv(&self) -> Option<T> {
        let mut locked_queue = self.messages.lock().unwrap();
        locked_queue.pop_front()
    }

    pub async fn recv(&self) -> T {
        let future = self.notify_on_sent.notified();
        tokio::pin!(future);

        loop {
            // Make sure that no wakeup is lost if we get
            // `None` from `try_recv`.
            future.as_mut().enable();

            if let Some(msg) = self.try_recv() {
                return msg;
            }

            // Wait for a call to `notify_one`.
            //
            // This uses `.as_mut()` to avoid consuming the future,
            // which lets us call `Pin::set` below.
            future.as_mut().await;

            // Reset the future in case another call to
            // `try_recv` got the message before us.
            future.set(self.notify_on_sent.notified());
        }
    }
}
```

[park]: std::thread::park
[unpark]: std::thread::Thread::unpark
[`notified().await`]: Notify::notified()
[`notify_one()`]: Notify::notify_one()
[`enable`]: Notified::enable()
[`Semaphore`]: crate::sync::Semaphore

## tokio::sync::notify::OwnedNotified (struct)

Future returned from [`Notify::notified_owned()`].

This future is fused, so once it has completed, any future calls to poll
will immediately return `Poll::Ready`.

## tokio::sync::once_cell::OnceCell (struct)

A thread-safe cell that can be written to only once.

A `OnceCell` is typically used for global variables that need to be
initialized once on first use, but need no further changes. The `OnceCell`
in Tokio allows the initialization procedure to be asynchronous.

### tokio::sync::once_cell::OnceCell (struct) › Examples

```
use tokio::sync::OnceCell;

async fn some_computation() -> u32 {
    1 + 1
}

static ONCE: OnceCell<u32> = OnceCell::const_new();

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let result = ONCE.get_or_init(some_computation).await;
assert_eq!(*result, 2);
# }
```

It is often useful to write a wrapper method for accessing the value.

```
use tokio::sync::OnceCell;

static ONCE: OnceCell<u32> = OnceCell::const_new();

async fn get_global_integer() -> &'static u32 {
    ONCE.get_or_init(|| async {
        1 + 1
    }).await
}

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let result = get_global_integer().await;
assert_eq!(*result, 2);
# }
```

## tokio::sync::once_cell::SetError (enum)

Errors that can be returned from [`OnceCell::set`].

[`OnceCell::set`]: crate::sync::OnceCell::set

## tokio::sync::once_cell::SetError::AlreadyInitializedError (variant)

The cell was already initialized when [`OnceCell::set`] was called.

[`OnceCell::set`]: crate::sync::OnceCell::set

## tokio::sync::once_cell::SetError::InitializingError (variant)

The cell is currently being initialized.

## tokio::sync::oneshot::Receiver (struct)

Receives a value from the associated [`Sender`].

A pair of both a [`Sender`] and a [`Receiver`]  are created by the
[`channel`](fn@channel) function.

This channel has no `recv` method because the receiver itself implements the
[`Future`] trait. To receive a `Result<T, `[`error::RecvError`]`>`, `.await` the `Receiver` object directly.

The `poll` method on the `Future` trait is allowed to spuriously return
`Poll::Pending` even if the message has been sent. If such a spurious
failure happens, then the caller will be woken when the spurious failure has
been resolved so that the caller can attempt to receive the message again.
Note that receiving such a wakeup does not guarantee that the next call will
succeed — it could fail with another spurious failure. (A spurious failure
does not mean that the message is lost. It is just delayed.)

[`Future`]: trait@std::future::Future

### tokio::sync::oneshot::Receiver (struct) › Cancel safety

Awaiting a `&mut Receiver<T>` is cancel safe. If it is used as a branch in
[`tokio::select!`](crate::select) and another branch completes first, it is
guaranteed that no message was received on this
channel.

### tokio::sync::oneshot::Receiver (struct) › Examples

```
use tokio::sync::oneshot;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, rx) = oneshot::channel();

tokio::spawn(async move {
    if let Err(_) = tx.send(3) {
        println!("the receiver dropped");
    }
});

match rx.await {
    Ok(v) => println!("got = {:?}", v),
    Err(_) => println!("the sender dropped"),
}
# }
```

If the sender is dropped without sending, the receiver will fail with
[`error::RecvError`]:

```
use tokio::sync::oneshot;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, rx) = oneshot::channel::<u32>();

tokio::spawn(async move {
    drop(tx);
});

match rx.await {
    Ok(_) => panic!("This doesn't happen"),
    Err(_) => println!("the sender dropped"),
}
# }
```

To use a `Receiver` in a `tokio::select!` loop, add `&mut` in front of the
channel.

```
use tokio::sync::oneshot;
use tokio::time::{interval, sleep, Duration};

# #[tokio::main(flavor = "current_thread")]
# async fn _doc() {}
# #[tokio::main(flavor = "current_thread", start_paused = true)]
# async fn main() {
let (send, mut recv) = oneshot::channel();
let mut interval = interval(Duration::from_millis(100));

# let handle =
tokio::spawn(async move {
    sleep(Duration::from_secs(1)).await;
    send.send("shut down").unwrap();
});

loop {
    tokio::select! {
        _ = interval.tick() => println!("Another 100ms"),
        msg = &mut recv => {
            println!("Got message: {}", msg.unwrap());
            break;
        }
    }
}
# handle.await.unwrap();
# }
```

## tokio::sync::oneshot::Sender (struct)

Sends a value to the associated [`Receiver`].

A pair of both a [`Sender`] and a [`Receiver`]  are created by the
[`channel`](fn@channel) function.

### tokio::sync::oneshot::Sender (struct) › Examples

```
use tokio::sync::oneshot;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, rx) = oneshot::channel();

tokio::spawn(async move {
    if let Err(_) = tx.send(3) {
        println!("the receiver dropped");
    }
});

match rx.await {
    Ok(v) => println!("got = {:?}", v),
    Err(_) => println!("the sender dropped"),
}
# }
```

If the sender is dropped without sending, the receiver will fail with
[`error::RecvError`]:

```
use tokio::sync::oneshot;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, rx) = oneshot::channel::<u32>();

tokio::spawn(async move {
    drop(tx);
});

match rx.await {
    Ok(_) => panic!("This doesn't happen"),
    Err(_) => println!("the sender dropped"),
}
# }
```

To use a `Sender` from a destructor, put it in an [`Option`] and call
[`Option::take`].

```
use tokio::sync::oneshot;

struct SendOnDrop {
    sender: Option<oneshot::Sender<&'static str>>,
}
impl Drop for SendOnDrop {
    fn drop(&mut self) {
        if let Some(sender) = self.sender.take() {
            // Using `let _ =` to ignore send errors.
            let _ = sender.send("I got dropped!");
        }
    }
}

# #[tokio::main(flavor = "current_thread")]
# async fn _doc() {}
# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (send, recv) = oneshot::channel();

let send_on_drop = SendOnDrop { sender: Some(send) };
drop(send_on_drop);

assert_eq!(recv.await, Ok("I got dropped!"));
# }
```

[`Option`]: std::option::Option
[`Option::take`]: std::option::Option::take

## tokio::sync::oneshot::channel (function)

Creates a new one-shot channel for sending single values across asynchronous
tasks.

The function returns separate "send" and "receive" handles. The `Sender`
handle is used by the producer to send the value. The `Receiver` handle is
used by the consumer to receive the value.

Each handle can be used on separate tasks.

### tokio::sync::oneshot::channel (function) › Examples

```
use tokio::sync::oneshot;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, rx) = oneshot::channel();

tokio::spawn(async move {
    if let Err(_) = tx.send(3) {
        println!("the receiver dropped");
    }
});

match rx.await {
    Ok(v) => println!("got = {:?}", v),
    Err(_) => println!("the sender dropped"),
}
# }
```

## tokio::sync::oneshot::error::RecvError (struct)

Error returned by the `Future` implementation for `Receiver`.

This error is returned by the receiver when the sender is dropped without sending.

## tokio::sync::oneshot::error::TryRecvError (enum)

Error returned by the `try_recv` function on `Receiver`.

## tokio::sync::oneshot::error::TryRecvError::Closed (variant)

The send half of the channel was dropped without sending a value.

## tokio::sync::oneshot::error::TryRecvError::Empty (variant)

The send half of the channel has not yet sent a value.

## tokio::sync::rwlock::RwLock (struct)

An asynchronous reader-writer lock.

This type of lock allows a number of readers or at most one writer at any
point in time. The write portion of this lock typically allows modification
of the underlying data (exclusive access) and the read portion of this lock
typically allows for read-only access (shared access).

In comparison, a [`Mutex`] does not distinguish between readers or writers
that acquire the lock, therefore causing any tasks waiting for the lock to
become available to yield. An `RwLock` will allow any number of readers to
acquire the lock as long as a writer is not holding the lock.

The priority policy of Tokio's read-write lock is _fair_ (or
[_write-preferring_]), in order to ensure that readers cannot starve
writers. Fairness is ensured using a first-in, first-out queue for the tasks
awaiting the lock; a read lock will not be given out until all write lock
requests that were queued before it have been acquired and released. This is
in contrast to the Rust standard library's `std::sync::RwLock`, where the
priority policy is dependent on the operating system's implementation.

The type parameter `T` represents the data that this lock protects. It is
required that `T` satisfies [`Send`] to be shared across threads. The RAII guards
returned from the locking methods implement [`Deref`](trait@std::ops::Deref)
(and [`DerefMut`](trait@std::ops::DerefMut)
for the `write` methods) to allow access to the content of the lock.

### tokio::sync::rwlock::RwLock (struct) › Examples

```
use tokio::sync::RwLock;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let lock = RwLock::new(5);

// many reader locks can be held at once
{
    let r1 = lock.read().await;
    let r2 = lock.read().await;
    assert_eq!(*r1, 5);
    assert_eq!(*r2, 5);
} // read locks are dropped at this point

// only one write lock may be held, however
{
    let mut w = lock.write().await;
    *w += 1;
    assert_eq!(*w, 6);
} // write lock is dropped here
# }
```

[`Mutex`]: struct@super::Mutex
[`RwLock`]: struct@RwLock
[`RwLockReadGuard`]: struct@RwLockReadGuard
[`RwLockWriteGuard`]: struct@RwLockWriteGuard
[`Send`]: trait@std::marker::Send
[_write-preferring_]: https://en.wikipedia.org/wiki/Readers%E2%80%93writer_lock#Priority_policies

## tokio::sync::rwlock::owned_read_guard::OwnedRwLockReadGuard (struct)

Owned RAII structure used to release the shared read access of a lock when
dropped.

This structure is created by the [`read_owned`] method on
[`RwLock`].

[`read_owned`]: method@crate::sync::RwLock::read_owned
[`RwLock`]: struct@crate::sync::RwLock

## tokio::sync::rwlock::owned_write_guard::OwnedRwLockWriteGuard (struct)

Owned RAII structure used to release the exclusive write access of a lock when
dropped.

This structure is created by the [`write_owned`] method
on [`RwLock`].

[`write_owned`]: method@crate::sync::RwLock::write_owned
[`RwLock`]: struct@crate::sync::RwLock

## tokio::sync::rwlock::owned_write_guard_mapped::OwnedRwLockMappedWriteGuard (struct)

Owned RAII structure used to release the exclusive write access of a lock when
dropped.

This structure is created by [mapping] an [`OwnedRwLockWriteGuard`]. It is a
separate type from `OwnedRwLockWriteGuard` to disallow downgrading a mapped
guard, since doing so can cause undefined behavior.

[mapping]: method@crate::sync::OwnedRwLockWriteGuard::map
[`OwnedRwLockWriteGuard`]: struct@crate::sync::OwnedRwLockWriteGuard

## tokio::sync::rwlock::read_guard::RwLockReadGuard (struct)

RAII structure used to release the shared read access of a lock when
dropped.

This structure is created by the [`read`] method on
[`RwLock`].

[`read`]: method@crate::sync::RwLock::read
[`RwLock`]: struct@crate::sync::RwLock

## tokio::sync::rwlock::write_guard::RwLockWriteGuard (struct)

RAII structure used to release the exclusive write access of a lock when
dropped.

This structure is created by the [`write`] method
on [`RwLock`].

[`write`]: method@crate::sync::RwLock::write
[`RwLock`]: struct@crate::sync::RwLock

## tokio::sync::rwlock::write_guard_mapped::RwLockMappedWriteGuard (struct)

RAII structure used to release the exclusive write access of a lock when
dropped.

This structure is created by [mapping] an [`RwLockWriteGuard`]. It is a
separate type from `RwLockWriteGuard` to disallow downgrading a mapped
guard, since doing so can cause undefined behavior.

[mapping]: method@crate::sync::RwLockWriteGuard::map
[`RwLockWriteGuard`]: struct@crate::sync::RwLockWriteGuard

## tokio::sync::semaphore::OwnedSemaphorePermit (struct)

An owned permit from the semaphore.

This type is created by the [`acquire_owned`] method.

[`acquire_owned`]: crate::sync::Semaphore::acquire_owned()

## tokio::sync::semaphore::Semaphore (struct)

Counting semaphore performing asynchronous permit acquisition.

A semaphore maintains a set of permits. Permits are used to synchronize
access to a shared resource. A semaphore differs from a mutex in that it
can allow more than one concurrent caller to access the shared resource at a
time.

When `acquire` is called and the semaphore has remaining permits, the
function immediately returns a permit. However, if no remaining permits are
available, `acquire` (asynchronously) waits until an outstanding permit is
dropped. At this point, the freed permit is assigned to the caller.

This `Semaphore` is fair, which means that permits are given out in the order
they were requested. This fairness is also applied when `acquire_many` gets
involved, so if a call to `acquire_many` at the front of the queue requests
more permits than currently available, this can prevent a call to `acquire`
from completing, even if the semaphore has enough permits complete the call
to `acquire`.

To use the `Semaphore` in a poll function, you can use the [`PollSemaphore`]
utility.

### tokio::sync::semaphore::Semaphore (struct) › Memory ordering

If a task writes some data and then releases a permit, any task that later
acquires a permit is guaranteed to see that data. This makes it safe to use
a semaphore to hand data off between tasks through shared state.

Stated more precisely in terms of atomic memory orderings: acquiring a
permit (via [`acquire`], [`acquire_many`], [`try_acquire`],
[`try_acquire_many`], or their `_owned` variants), releasing permits (by
dropping a [`SemaphorePermit`] or [`OwnedSemaphorePermit`], or by calling
[`add_permits`] or [`forget_permits`]), and closing the semaphore (via
[`close`]) are all `AcqRel` operations. They are totally ordered, and each
one synchronizes-with all such operations that precede it, giving the same
guarantees as `AcqRel` operations on a single atomic.

A failed acquisition attempt (including [`TryAcquireError::NoPermits`] and
[`TryAcquireError::Closed`]), along with the [`available_permits`] and
[`is_closed`] methods, behave like an `Acquire` load.

[`acquire`]: Semaphore::acquire
[`acquire_many`]: Semaphore::acquire_many
[`try_acquire`]: Semaphore::try_acquire
[`try_acquire_many`]: Semaphore::try_acquire_many
[`add_permits`]: Semaphore::add_permits
[`forget_permits`]: Semaphore::forget_permits
[`close`]: Semaphore::close
[`available_permits`]: Semaphore::available_permits
[`is_closed`]: Semaphore::is_closed

### tokio::sync::semaphore::Semaphore (struct) › Examples

Basic usage:

```
use tokio::sync::{Semaphore, TryAcquireError};

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let semaphore = Semaphore::new(3);

let a_permit = semaphore.acquire().await.unwrap();
let two_permits = semaphore.acquire_many(2).await.unwrap();

assert_eq!(semaphore.available_permits(), 0);

let permit_attempt = semaphore.try_acquire();
assert_eq!(permit_attempt.err(), Some(TryAcquireError::NoPermits));
# }
```

### tokio::sync::semaphore::Semaphore (struct) › Limit the number of simultaneously opened files in your program

Most operating systems have limits on the number of open file
handles. Even in systems without explicit limits, resource constraints
implicitly set an upper bound on the number of open files. If your
program attempts to open a large number of files and exceeds this
limit, it will result in an error.

This example uses a Semaphore with 100 permits. By acquiring a permit from
the Semaphore before accessing a file, you ensure that your program opens
no more than 100 files at a time. When trying to open the 101st
file, the program will wait until a permit becomes available before
proceeding to open another file.
```
# #[cfg(not(target_family = "wasm"))]
# {
use std::io::Result;
use tokio::fs::File;
use tokio::sync::Semaphore;
use tokio::io::AsyncWriteExt;

static PERMITS: Semaphore = Semaphore::const_new(100);

async fn write_to_file(message: &[u8]) -> Result<()> {
    let _permit = PERMITS.acquire().await.unwrap();
    let mut buffer = File::create("example.txt").await?;
    buffer.write_all(message).await?;
    Ok(()) // Permit goes out of scope here, and is available again for acquisition
}
# }
```

### tokio::sync::semaphore::Semaphore (struct) › Limit the number of outgoing requests being sent at the same time

In some scenarios, it might be required to limit the number of outgoing
requests being sent in parallel. This could be due to limits of a consumed
API or the network resources of the system the application is running on.

This example uses an `Arc<Semaphore>` with 10 permits. Each task spawned is
given a reference to the semaphore by cloning the `Arc<Semaphore>`. Before
a task sends a request, it must acquire a permit from the semaphore by
calling [`Semaphore::acquire`]. This ensures that at most 10 requests are
sent in parallel at any given time. After a task has sent a request, it
drops the permit to allow other tasks to send requests.

```
use std::sync::Arc;
use tokio::sync::Semaphore;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
// Define maximum number of parallel requests.
let semaphore = Arc::new(Semaphore::new(5));
// Spawn many tasks that will send requests.
let mut jhs = Vec::new();
for task_id in 0..50 {
    let semaphore = semaphore.clone();
    let jh = tokio::spawn(async move {
        // Acquire permit before sending request.
        let _permit = semaphore.acquire().await.unwrap();
        // Send the request.
        let response = send_request(task_id).await;
        // Drop the permit after the request has been sent.
        drop(_permit);
        // Handle response.
        // ...

        response
    });
    jhs.push(jh);
}
// Collect responses from tasks.
let mut responses = Vec::new();
for jh in jhs {
    let response = jh.await.unwrap();
    responses.push(response);
}
// Process responses.
// ...
# }
# async fn send_request(task_id: usize) {
#     // Send request.
# }
```

### tokio::sync::semaphore::Semaphore (struct) › Limit the number of incoming requests being handled at the same time

Similar to limiting the number of simultaneously opened files, network handles
are a limited resource. Allowing an unbounded amount of requests to be processed
could result in a denial-of-service, among many other issues.

This example uses an `Arc<Semaphore>` instead of a global variable.
To limit the number of requests that can be processed at the time,
we acquire a permit for each task before spawning it. Once acquired,
a new task is spawned; and once finished, the permit is dropped inside
of the task to allow others to spawn. Permits must be acquired via
[`Semaphore::acquire_owned`] to be movable across the task boundary.
(Since our semaphore is not a global variable — if it was, then `acquire` would be enough.)

```no_run
# #[cfg(not(target_family = "wasm"))]
# {
use std::sync::Arc;
use tokio::sync::Semaphore;
use tokio::net::TcpListener;

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let semaphore = Arc::new(Semaphore::new(3));
    let listener = TcpListener::bind("127.0.0.1:8080").await?;

    loop {
        // Acquire permit before accepting the next socket.
        //
        // We use `acquire_owned` so that we can move `permit` into
        // other tasks.
        let permit = semaphore.clone().acquire_owned().await.unwrap();
        let (mut socket, _) = listener.accept().await?;

        tokio::spawn(async move {
            // Do work using the socket.
            handle_connection(&mut socket).await;
            // Drop socket while the permit is still live.
            drop(socket);
            // Drop the permit, so more tasks can be created.
            drop(permit);
        });
    }
}
# async fn handle_connection(_socket: &mut tokio::net::TcpStream) {
#   // Do work
# }
# }
```

### tokio::sync::semaphore::Semaphore (struct) › Prevent tests from running in parallel

By default, Rust runs tests in the same file in parallel. However, in some
cases, running two tests in parallel may lead to problems. For example, this
can happen when tests use the same database.

Consider the following scenario:
1. `test_insert`: Inserts a key-value pair into the database, then retrieves
   the value using the same key to verify the insertion.
2. `test_update`: Inserts a key, then updates the key to a new value and
   verifies that the value has been accurately updated.
3. `test_others`: A third test that doesn't modify the database state. It
   can run in parallel with the other tests.

In this example, `test_insert` and `test_update` need to run in sequence to
work, but it doesn't matter which test runs first. We can leverage a
semaphore with a single permit to address this challenge.

```
# use tokio::sync::Mutex;
# use std::collections::BTreeMap;
# struct Database {
#   map: Mutex<BTreeMap<String, i32>>,
# }
# impl Database {
#    pub const fn setup() -> Database {
#        Database {
#            map: Mutex::const_new(BTreeMap::new()),
#        }
#    }
#    pub async fn insert(&self, key: &str, value: i32) {
#        self.map.lock().await.insert(key.to_string(), value);
#    }
#    pub async fn update(&self, key: &str, value: i32) {
#        self.map.lock().await
#            .entry(key.to_string())
#            .and_modify(|origin| *origin = value);
#    }
#    pub async fn delete(&self, key: &str) {
#        self.map.lock().await.remove(key);
#    }
#    pub async fn get(&self, key: &str) -> i32 {
#        *self.map.lock().await.get(key).unwrap()
#    }
# }
use tokio::sync::Semaphore;

// Initialize a static semaphore with only one permit, which is used to
// prevent test_insert and test_update from running in parallel.
static PERMIT: Semaphore = Semaphore::const_new(1);

// Initialize the database that will be used by the subsequent tests.
static DB: Database = Database::setup();

#[tokio::test]
# async fn fake_test_insert() {}
async fn test_insert() {
    // Acquire permit before proceeding. Since the semaphore has only one permit,
    // the test will wait if the permit is already acquired by other tests.
    let permit = PERMIT.acquire().await.unwrap();

    // Do the actual test stuff with database

    // Insert a key-value pair to database
    let (key, value) = ("name", 0);
    DB.insert(key, value).await;

    // Verify that the value has been inserted correctly.
    assert_eq!(DB.get(key).await, value);

    // Undo the insertion, so the database is empty at the end of the test.
    DB.delete(key).await;

    // Drop permit. This allows the other test to start running.
    drop(permit);
}

#[tokio::test]
# async fn fake_test_update() {}
async fn test_update() {
    // Acquire permit before proceeding. Since the semaphore has only one permit,
    // the test will wait if the permit is already acquired by other tests.
    let permit = PERMIT.acquire().await.unwrap();

    // Do the same insert.
    let (key, value) = ("name", 0);
    DB.insert(key, value).await;

    // Update the existing value with a new one.
    let new_value = 1;
    DB.update(key, new_value).await;

    // Verify that the value has been updated correctly.
    assert_eq!(DB.get(key).await, new_value);

    // Undo any modificattion.
    DB.delete(key).await;

    // Drop permit. This allows the other test to start running.
    drop(permit);
}

#[tokio::test]
# async fn fake_test_others() {}
async fn test_others() {
    // This test can run in parallel with test_insert and test_update,
    // so it does not use PERMIT.
}
# #[tokio::main(flavor = "current_thread")]
# async fn main() {
#   test_insert().await;
#   test_update().await;
#   test_others().await;
# }
```

### tokio::sync::semaphore::Semaphore (struct) › Rate limiting using a token bucket

This example showcases the [`add_permits`] and [`SemaphorePermit::forget`] methods.

Many applications and systems have constraints on the rate at which certain
operations should occur. Exceeding this rate can result in suboptimal
performance or even errors.

This example implements rate limiting using a [token bucket]. A token bucket is a form of rate
limiting that doesn't kick in immediately, to allow for short bursts of incoming requests that
arrive at the same time.

With a token bucket, each incoming request consumes a token, and the tokens are refilled at a
certain rate that defines the rate limit. When a burst of requests arrives, tokens are
immediately given out until the bucket is empty. Once the bucket is empty, requests will have to
wait for new tokens to be added.

Unlike the example that limits how many requests can be handled at the same time, we do not add
tokens back when we finish handling a request. Instead, tokens are added only by a timer task.

Note that this implementation is suboptimal when the duration is small, because it consumes a
lot of cpu constantly looping and sleeping.

[token bucket]: https://en.wikipedia.org/wiki/Token_bucket
[`add_permits`]: crate::sync::Semaphore::add_permits
[`SemaphorePermit::forget`]: crate::sync::SemaphorePermit::forget
```
use std::sync::Arc;
use tokio::sync::Semaphore;
use tokio::time::{interval, Duration};

struct TokenBucket {
    sem: Arc<Semaphore>,
    jh: tokio::task::JoinHandle<()>,
}

impl TokenBucket {
    fn new(duration: Duration, capacity: usize) -> Self {
        let sem = Arc::new(Semaphore::new(capacity));

        // refills the tokens at the end of each interval
        let jh = tokio::spawn({
            let sem = sem.clone();
            let mut interval = interval(duration);
            interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);

            async move {
                loop {
                    interval.tick().await;

                    if sem.available_permits() < capacity {
                        sem.add_permits(1);
                    }
                }
            }
        });

        Self { jh, sem }
    }

    async fn acquire(&self) {
        // This can return an error if the semaphore is closed, but we
        // never close it, so this error can never happen.
        let permit = self.sem.acquire().await.unwrap();
        // To avoid releasing the permit back to the semaphore, we use
        // the `SemaphorePermit::forget` method.
        permit.forget();
    }
}

impl Drop for TokenBucket {
    fn drop(&mut self) {
        // Kill the background task so it stops taking up resources when we
        // don't need it anymore.
        self.jh.abort();
    }
}

# #[tokio::main(flavor = "current_thread")]
# async fn _hidden() {}
# #[tokio::main(flavor = "current_thread", start_paused = true)]
# async fn main() {
let capacity = 5;
let update_interval = Duration::from_secs_f32(1.0 / capacity as f32);
let bucket = TokenBucket::new(update_interval, capacity);

for _ in 0..5 {
    bucket.acquire().await;

    // do the operation
}
# }
```

[`PollSemaphore`]: https://docs.rs/tokio-util/latest/tokio_util/sync/struct.PollSemaphore.html
[`Semaphore::acquire_owned`]: crate::sync::Semaphore::acquire_owned

## tokio::sync::semaphore::SemaphorePermit (struct)

A permit from the semaphore.

This type is created by the [`acquire`] method.

[`acquire`]: crate::sync::Semaphore::acquire()

## tokio::sync::set_once::SetOnce (struct)

A thread-safe cell that can be written to only once.

A `SetOnce` is inspired from python's [`asyncio.Event`] type. It can be
used to wait until the value of the `SetOnce` is set like a "Event" mechanism.

### tokio::sync::set_once::SetOnce (struct) › Example

```
use tokio::sync::{SetOnce, SetOnceError};

static ONCE: SetOnce<u32> = SetOnce::const_new();

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> Result<(), SetOnceError<u32>> {

// set the value inside a task somewhere...
tokio::spawn(async move { ONCE.set(20) });

// checking with .get doesn't block main thread
println!("{:?}", ONCE.get());

// wait until the value is set, blocks the thread
println!("{:?}", ONCE.wait().await);

Ok(())
# }
```

A `SetOnce` is typically used for global variables that need to be
initialized once on first use, but need no further changes. The `SetOnce`
in Tokio allows the initialization procedure to be asynchronous.

### tokio::sync::set_once::SetOnce (struct) › Example

```
use tokio::sync::{SetOnce, SetOnceError};
use std::sync::Arc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> Result<(), SetOnceError<u32>> {
let once = SetOnce::new();

let arc = Arc::new(once);
let first_cl = Arc::clone(&arc);
let second_cl = Arc::clone(&arc);

// set the value inside a task
tokio::spawn(async move { first_cl.set(20) }).await.unwrap()?;

// wait inside task to not block the main thread
tokio::spawn(async move {
    // wait inside async context for the value to be set
    assert_eq!(*second_cl.wait().await, 20);
}).await.unwrap();

// subsequent set calls will fail
assert!(arc.set(30).is_err());

println!("{:?}", arc.get());

Ok(())
# }
```

[`asyncio.Event`]: https://docs.python.org/3/library/asyncio-sync.html#asyncio.Event

## tokio::sync::set_once::SetOnceError (struct)

Error that can be returned from [`SetOnce::set`].

This error means that the `SetOnce` was already initialized when
set was called

[`SetOnce::set`]: crate::sync::SetOnce::set

## tokio::sync::watch::Receiver (struct)

Receives values from the associated [`Sender`](struct@Sender).

Instances are created by the [`channel`](fn@channel) function.

To turn this receiver into a `Stream`, you can use the [`WatchStream`]
wrapper.

[`WatchStream`]: https://docs.rs/tokio-stream/0.1/tokio_stream/wrappers/struct.WatchStream.html

## tokio::sync::watch::Ref (struct)

Returns a reference to the inner value.

Outstanding borrows hold a read lock on the inner value. This means that
long-lived borrows could cause the producer half to block. It is recommended
to keep the borrow as short-lived as possible. Additionally, if you are
running in an environment that allows `!Send` futures, you must ensure that
the returned `Ref` type is never held alive across an `.await` point,
otherwise, it can lead to a deadlock.

The priority policy of the lock is dependent on the underlying lock
implementation, and this type does not guarantee that any particular policy
will be used. In particular, a producer which is waiting to acquire the lock
in `send` might or might not block concurrent calls to `borrow`, e.g.:

<details><summary>Potential deadlock example</summary>

```text
// Task 1 (on thread A)    |  // Task 2 (on thread B)
let _ref1 = rx.borrow();   |
                           |  // will block
                           |  let _ = tx.send(());
// may deadlock            |
let _ref2 = rx.borrow();   |
```
</details>

## tokio::sync::watch::Sender (struct)

Sends values to the associated [`Receiver`](struct@Receiver).

Instances are created by the [`channel`](fn@channel) function.

## tokio::sync::watch::channel (function)

Creates a new watch channel, returning the "send" and "receive" handles.

All values sent by [`Sender`] will become visible to the [`Receiver`] handles.
Only the last value sent is made available to the [`Receiver`] half. All
intermediate values are dropped.

### tokio::sync::watch::channel (function) › Examples

The following example prints `hello! world! `.

```
use tokio::sync::watch;
use tokio::time::{Duration, sleep};

# async fn dox() -> Result<(), Box<dyn std::error::Error>> {
let (tx, mut rx) = watch::channel("hello");

tokio::spawn(async move {
    // Use the equivalent of a "do-while" loop so the initial value is
    // processed before awaiting the `changed()` future.
    loop {
        println!("{}! ", *rx.borrow_and_update());
        if rx.changed().await.is_err() {
            break;
        }
    }
});

sleep(Duration::from_millis(100)).await;
tx.send("world")?;
# Ok(())
# }
```

[`Sender`]: struct@Sender
[`Receiver`]: struct@Receiver

## tokio::sync::watch::error::RecvError (struct)

Error produced when receiving a change notification.

## tokio::sync::watch::error::SendError (struct)

Error produced when sending a value fails.

## tokio::sync_all (function)

Attempts to sync all OS-internal metadata to disk.

This function will attempt to ensure that all in-core data reaches the
filesystem before returning.

### tokio::sync_all (function) › Examples

```no_run
use tokio::fs::File;
use tokio::io::AsyncWriteExt;

# async fn dox() -> std::io::Result<()> {
let mut file = File::create("foo.txt").await?;
file.write_all(b"hello, world!").await?;
file.sync_all().await?;
# Ok(())
# }
```

The [`write_all`] method is defined on the [`AsyncWriteExt`] trait.

[`write_all`]: fn@crate::io::AsyncWriteExt::write_all
[`AsyncWriteExt`]: trait@crate::io::AsyncWriteExt

## tokio::sync_data (function)

This function is similar to `sync_all`, except that it may not
synchronize file metadata to the filesystem.

This is intended for use cases that must synchronize content, but don't
need the metadata on disk. The goal of this method is to reduce disk
operations.

Note that some platforms may simply implement this in terms of `sync_all`.

### tokio::sync_data (function) › Examples

```no_run
use tokio::fs::File;
use tokio::io::AsyncWriteExt;

# async fn dox() -> std::io::Result<()> {
let mut file = File::create("foo.txt").await?;
file.write_all(b"hello, world!").await?;
file.sync_data().await?;
# Ok(())
# }
```

The [`write_all`] method is defined on the [`AsyncWriteExt`] trait.

[`write_all`]: fn@crate::io::AsyncWriteExt::write_all
[`AsyncWriteExt`]: trait@crate::io::AsyncWriteExt

## tokio::sync_scope (function)

Sets a value `T` as the task-local value for the closure `F`.

On completion of `sync_scope`, the task-local will be dropped.

### tokio::sync_scope (function) › Panics

This method panics if called inside a call to [`with`] or [`try_with`]
on the same `LocalKey`.

### tokio::sync_scope (function) › Examples

```
# async fn dox() {
tokio::task_local! {
    static NUMBER: u32;
}

NUMBER.sync_scope(1, || {
    println!("task local value: {}", NUMBER.get());
});
# }
```

[`with`]: fn@Self::with
[`try_with`]: fn@Self::try_with

## tokio::take (function)

Creates an adaptor which reads at most `limit` bytes from it.

This function returns a new instance of `AsyncRead` which will read
at most `limit` bytes, after which it will always return EOF
(`Ok(0)`). Any read errors will not count towards the number of
bytes read and future calls to [`read()`] may succeed.

[`read()`]: fn@crate::io::AsyncReadExt::read

[read]: AsyncReadExt::read

### tokio::take (function) › Examples

[`File`][crate::fs::File]s implement `Read`:

```no_run
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::io::{self, AsyncReadExt};
use tokio::fs::File;

#[tokio::main]
async fn main() -> io::Result<()> {
    let f = File::open("foo.txt").await?;
    let mut buffer = [0; 5];

    // read at most five bytes
    let mut handle = f.take(5);

    handle.read(&mut buffer).await?;
    Ok(())
}
# }
```

## tokio::take (function)

Returns a new `ReadBuf` comprised of the unfilled section up to `n`.

## tokio::take (function)

Takes ownership of the current value, leaving the cell empty.  Returns
`None` if the cell is empty.

## tokio::take_error (function)

Returns the value of the `SO_ERROR` option.

## tokio::take_error (function)

Returns the value of the `SO_ERROR` option.

## tokio::take_error (function)

Returns the value of the `SO_ERROR` option.

## tokio::take_error (function)

Returns the value of the `SO_ERROR` option.

## tokio::take_error (function)

Returns the value of the `SO_ERROR` option.

### tokio::take_error (function) › Examples
```
use tokio::net::UdpSocket;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
#   if cfg!(miri) { return Ok(()); } // No UDP sockets in miri.
    // Create a socket
    let socket = UdpSocket::bind("0.0.0.0:8080").await?;

    if let Ok(Some(err)) = socket.take_error() {
        println!("Got error: {:?}", err);
    }

    Ok(())
}
```

## tokio::take_value (function)

Returns the value stored in the task local by this `TaskLocalFuture`.

The function returns:

* `Some(T)` if the task local value exists.
* `None` if the task local value has already been taken.

Note that this function attempts to take the task local value even if
the future has not yet completed. In that case, the value will no longer
be available via the task local after the call to `take_value`.

### tokio::take_value (function) › Examples

```
# async fn dox() {
tokio::task_local! {
    static KEY: u32;
}

let fut = KEY.scope(42, async {
    // Do some async work
});

let mut pinned = Box::pin(fut);

// Complete the TaskLocalFuture
let _ = pinned.as_mut().await;

// And here, we can take task local value
let value = pinned.as_mut().take_value();

assert_eq!(value, Some(42));
# }
```

## tokio::task::blocking::block_in_place (function)

Runs the provided blocking function on the current thread without
blocking the executor.

In general, issuing a blocking call or performing a lot of compute in a
future without yielding is problematic, as it may prevent the executor
from driving other tasks forward. Calling this function informs the
executor that the currently executing task is about to block the thread,
so the executor is able to hand off any other tasks it has to a new
worker thread before that happens. See the [CPU-bound tasks and blocking
code][blocking] section for more information.

Be aware that although this function avoids starving other independently
spawned tasks, any other code running concurrently in the same task will
be suspended during the call to `block_in_place`. This can happen e.g.
when using the [`join!`] macro. To avoid this issue, use
[`spawn_blocking`] instead of `block_in_place`.

Note that this function cannot be used within a [`current_thread`] runtime
because in this case there are no other worker threads to hand off tasks
to. On the other hand, calling the function outside a runtime is
allowed. In this case, `block_in_place` just calls the provided closure
normally.

Code running behind `block_in_place` cannot be cancelled. When you shut
down the executor, it will wait indefinitely for all blocking operations
to finish. You can use [`shutdown_timeout`] to stop waiting for them
after a certain timeout. Be aware that this will still not cancel the
tasks — they are simply allowed to keep running after the method
returns.

[blocking]: ../index.html#cpu-bound-tasks-and-blocking-code
[`spawn_blocking`]: fn@crate::task::spawn_blocking
[`join!`]: macro@join
[`thread::spawn`]: fn@std::thread::spawn
[`shutdown_timeout`]: fn@crate::runtime::Runtime::shutdown_timeout

### tokio::task::blocking::block_in_place (function) › Examples

```
use tokio::task;

# async fn docs() {
task::block_in_place(move || {
    // do some compute-heavy work or call synchronous code
});
# }
```

Code running inside `block_in_place` may use `block_on` to reenter the
async context.

```
use tokio::task;
use tokio::runtime::Handle;

# async fn docs() {
task::block_in_place(move || {
    Handle::current().block_on(async move {
        // do something async
    });
});
# }
```

### tokio::task::blocking::block_in_place (function) › Panics

This function panics if called from a [`current_thread`] runtime.

[`current_thread`]: fn@crate::runtime::Builder::new_current_thread

## tokio::task::blocking::spawn_blocking (function)

Runs the provided closure on a thread where blocking is acceptable.

In general, issuing a blocking call or performing a lot of compute in a
future without yielding is problematic, as it may prevent the executor from
driving other futures forward. This function runs the provided closure on a
thread dedicated to blocking operations. See the [CPU-bound tasks and
blocking code][blocking] section for more information.

Tokio will spawn more blocking threads when they are requested through this
function until the upper limit configured on the [`Builder`] is reached.
After reaching the upper limit, the tasks are put in a queue.
The thread limit is very large by default, because `spawn_blocking` is often
used for various kinds of IO operations that cannot be performed
asynchronously.  When you run CPU-bound code using `spawn_blocking`, you
should keep this large upper limit in mind. When running many CPU-bound
computations, a semaphore or some other synchronization primitive should be
used to limit the number of computations executed in parallel. Specialized
CPU-bound executors, such as [rayon], may also be a good fit.

This function is intended for non-async operations that eventually finish on
their own. If you want to spawn an ordinary thread, you should use
[`thread::spawn`] instead.

Be aware that tasks spawned using `spawn_blocking` cannot be aborted
because they are not async. If you call [`abort`] on a `spawn_blocking`
task, then this *will not have any effect*, and the task will continue
running normally. The exception is if the task has not started running
yet; in that case, calling `abort` may prevent the task from starting.

When you shut down the executor, it will attempt to `abort` all tasks
including `spawn_blocking` tasks. However, `spawn_blocking` tasks
cannot be aborted once they start running, which means that runtime
shutdown will wait indefinitely for all started `spawn_blocking` to
finish running. You can use [`shutdown_timeout`] to stop waiting for
them after a certain timeout. Be aware that this will still not cancel
the tasks — they are simply allowed to keep running after the method
returns. It is possible for a blocking task to be cancelled if it has
not yet started running, but this is not guaranteed.

### tokio::task::blocking::spawn_blocking (function) › When to use `spawn_blocking` vs dedicated threads

`spawn_blocking` is intended for *bounded* blocking work that eventually finishes.
Each call occupies a thread from the runtime's blocking thread pool for the duration
of the task. Long-lived tasks therefore reduce the pool's effective capacity, which
can delay other blocking operations once the pool is saturated and work is queued.

For workloads that run indefinitely or for extended periods (for example,
background workers or persistent processing loops), prefer a dedicated thread created with
[`thread::spawn`].

As a rule of thumb:
- Use `spawn_blocking` for short-lived blocking operations
- Use dedicated threads for long-lived or persistent blocking workloads

Note that if you are using the single threaded runtime, this function will
still spawn additional threads for blocking operations. The current-thread
scheduler's single thread is only used for asynchronous code.

### tokio::task::blocking::spawn_blocking (function) › Related APIs and patterns for bridging asynchronous and blocking code

In simple cases, it is sufficient to have the closure accept input
parameters at creation time and return a single value (or struct/tuple, etc.).

For more complex situations in which it is desirable to stream data to or from
the synchronous context, the [`mpsc channel`] has `blocking_send` and
`blocking_recv` methods for use in non-async code such as the thread created
by `spawn_blocking`.

Another option is [`SyncIoBridge`] for cases where the synchronous context
is operating on byte streams.  For example, you might use an asynchronous
HTTP client such as [hyper] to fetch data, but perform complex parsing
of the payload body using a library written for synchronous I/O.

Finally, see also [Bridging with sync code][bridgesync] for discussions
around the opposite case of using Tokio as part of a larger synchronous
codebase.

[`Builder`]: struct@crate::runtime::Builder
[blocking]: ../index.html#cpu-bound-tasks-and-blocking-code
[rayon]: https://docs.rs/rayon
[`mpsc channel`]: crate::sync::mpsc
[`SyncIoBridge`]: https://docs.rs/tokio-util/latest/tokio_util/io/struct.SyncIoBridge.html
[hyper]: https://docs.rs/hyper
[`thread::spawn`]: fn@std::thread::spawn
[`shutdown_timeout`]: fn@crate::runtime::Runtime::shutdown_timeout
[bridgesync]: https://tokio.rs/tokio/topics/bridging
[`AtomicBool`]: struct@std::sync::atomic::AtomicBool
[`abort`]: crate::task::JoinHandle::abort

### tokio::task::blocking::spawn_blocking (function) › Examples

Pass an input value and receive result of computation:

```
use tokio::task;

# async fn docs() -> Result<(), Box<dyn std::error::Error>>{
// Initial input
let mut v = "Hello, ".to_string();
let res = task::spawn_blocking(move || {
    // Stand-in for compute-heavy work or using synchronous APIs
    v.push_str("world");
    // Pass ownership of the value back to the asynchronous context
    v
}).await?;

// `res` is the value returned from the thread
assert_eq!(res.as_str(), "Hello, world");
# Ok(())
# }
```

Use a channel:

```
use tokio::task;
use tokio::sync::mpsc;

# async fn docs() {
let (tx, mut rx) = mpsc::channel(2);
let start = 5;
let worker = task::spawn_blocking(move || {
    for x in 0..10 {
        // Stand in for complex computation
        tx.blocking_send(start + x).unwrap();
    }
});

let mut acc = 0;
while let Some(v) = rx.recv().await {
    acc += v;
}
assert_eq!(acc, 95);
worker.await.unwrap();
# }
```

## tokio::task::builder::Builder (struct)

Factory which is used to configure the properties of a new task.

**Note**: This is an [unstable API][unstable]. The public API of this type
may break in 1.x releases. See [the documentation on unstable
features][unstable] for details.

Methods can be chained in order to configure it.

Currently, there is only one configuration option:

- [`name`], which specifies an associated name for
  the task

There are three types of task that can be spawned from a Builder:
- [`spawn_local`] for executing not [`Send`] futures
- [`spawn`] for executing [`Send`] futures on the runtime
- [`spawn_blocking`] for executing blocking code in the
  blocking thread pool.

### tokio::task::builder::Builder (struct) › Example

```no_run
use tokio::net::{TcpListener, TcpStream};

use std::io;

async fn process(socket: TcpStream) {
    // ...
# drop(socket);
}

#[tokio::main]
async fn main() -> io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:8080").await?;

    loop {
        let (socket, _) = listener.accept().await?;

        tokio::task::Builder::new()
            .name("tcp connection handler")
            .spawn(async move {
                // Process each socket concurrently.
                process(socket).await
            })?;
    }
}
```
[unstable]: crate#unstable-features
[`name`]: Builder::name
[`spawn_local`]: Builder::spawn_local
[`spawn`]: Builder::spawn
[`spawn_blocking`]: Builder::spawn_blocking

## tokio::task::coop::Coop (struct)

Future wrapper to ensure cooperative scheduling created by [`cooperative`].

## tokio::task::coop::RestoreOnPending (struct)

Value returned by the [`poll_proceed`] method.

## tokio::task::coop::consume_budget::consume_budget (function)

Consumes a unit of budget and returns the execution back to the Tokio
runtime *if* the task's coop budget was exhausted.

The task will only yield if its entire coop budget has been exhausted.
This function can be used in order to insert optional yield points into long
computations that do not use Tokio resources like sockets or semaphores,
without redundantly yielding to the runtime each time.

### tokio::task::coop::consume_budget::consume_budget (function) › Examples

Make sure that a function which returns a sum of (potentially lots of)
iterated values is cooperative.

```
async fn sum_iterator(input: &mut impl std::iter::Iterator<Item=i64>) -> i64 {
    let mut sum: i64 = 0;
    while let Some(i) = input.next() {
        sum += i;
        tokio::task::consume_budget().await
    }
    sum
}
```

## tokio::task::coop::cooperative (function)

Creates a wrapper future that makes the inner future cooperate with the Tokio scheduler.

When polled, the wrapper will first call [`poll_proceed`] to consume task budget, and
immediately yield if the budget has been depleted. If budget was available, the inner future
is polled. The budget consumption will be made final using [`RestoreOnPending::made_progress`]
if the inner future resolves to its final value.

### tokio::task::coop::cooperative (function) › Examples

When you call `recv` on the `Receiver` of a [`tokio::sync::mpsc`](crate::sync::mpsc)
channel, task budget will automatically be consumed when the next value is returned.
This makes tasks that use Tokio mpsc channels automatically cooperative.

If you're using [`futures::channel::mpsc`](https://docs.rs/futures/latest/futures/channel/mpsc/index.html)
instead, automatic task budget consumption will not happen. This example shows how can use
`cooperative` to make `futures::channel::mpsc` channels cooperate with the scheduler in the
same way Tokio channels do.

```
use tokio::task::coop::cooperative;
use futures::channel::mpsc::Receiver;
use futures::stream::StreamExt;

async fn receive_next<T>(receiver: &mut Receiver<T>) -> Option<T> {
    // Use `StreamExt::next` to obtain a `Future` that resolves to the next value
    let recv_future = receiver.next();
    // Wrap it a cooperative wrapper
    let coop_future = cooperative(recv_future);
    // And await
    coop_future.await
}
```

## tokio::task::coop::has_budget_remaining (function)

 Returns `true` if there is still budget left on the task.

### tokio::task::coop::has_budget_remaining (function) › Examples

 This example defines a `Timeout` future that requires a given `future` to complete before the
 specified duration elapses. If it does, its result is returned; otherwise, an error is returned
 and the future is canceled.

 Note that the future could exhaust the budget before we evaluate the timeout. Using `has_budget_remaining`,
 we can detect this scenario and ensure the timeout is always checked.

 ```
 # use std::future::Future;
 # use std::pin::{pin, Pin};
 # use std::task::{ready, Context, Poll};
 # use tokio::task::coop;
 # use tokio::time::Sleep;
 pub struct Timeout<T> {
     future: T,
     delay: Pin<Box<Sleep>>,
 }

 impl<T> Future for Timeout<T>
 where
     T: Future + Unpin,
 {
     type Output = Result<T::Output, ()>;

     fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
         let this = Pin::into_inner(self);
         let future = Pin::new(&mut this.future);
         let delay = Pin::new(&mut this.delay);

         // check if the future is ready
         let had_budget_before = coop::has_budget_remaining();
         if let Poll::Ready(v) = future.poll(cx) {
             return Poll::Ready(Ok(v));
         }
         let has_budget_now = coop::has_budget_remaining();

         // evaluate the timeout
         if let (true, false) = (had_budget_before, has_budget_now) {
             // it is the underlying future that exhausted the budget
             ready!(pin!(coop::unconstrained(delay)).poll(cx));
         } else {
             ready!(delay.poll(cx));
         }
         return Poll::Ready(Err(()));
     }
 }
```

## tokio::task::coop::poll_proceed (function)

Decrements the task budget and returns [`Poll::Pending`] if the budget is depleted.
This indicates that the task should yield to the scheduler. Otherwise, returns
[`RestoreOnPending`] which can be used to commit the budget consumption.

The returned [`RestoreOnPending`] will revert the budget to its former
value when dropped unless [`RestoreOnPending::made_progress`]
is called. It is the caller's responsibility to do so when it _was_ able to
make progress after the call to [`poll_proceed`].
Restoring the budget automatically ensures the task can try to make progress in some other
way.

Note that [`RestoreOnPending`] restores the budget **as it was before [`poll_proceed`]**.
Therefore, if the budget is _further_ adjusted between when [`poll_proceed`] returns and
[`RestoreOnPending`] is dropped, those adjustments are erased unless the caller indicates
that progress was made.

### tokio::task::coop::poll_proceed (function) › Examples

This example wraps the `futures::channel::mpsc::UnboundedReceiver` to
cooperate with the Tokio scheduler. Each time a value is received, task budget
is consumed. If no budget is available, the task yields to the scheduler.

```
use std::pin::Pin;
use std::task::{ready, Context, Poll};
use tokio::task::coop;
use futures::stream::{Stream, StreamExt};
use futures::channel::mpsc::UnboundedReceiver;

struct CoopUnboundedReceiver<T> {
   receiver: UnboundedReceiver<T>,
}

impl<T> Stream for CoopUnboundedReceiver<T> {
    type Item = T;
    fn poll_next(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>
    ) -> Poll<Option<T>> {
        let coop = ready!(coop::poll_proceed(cx));
        match self.receiver.poll_next_unpin(cx) {
            Poll::Ready(v) => {
                // We received a value, so consume budget.
                coop.made_progress();
                Poll::Ready(v)
            }
            Poll::Pending => Poll::Pending,
       }
    }
}
```

## tokio::task::coop::unconstrained::Unconstrained (struct)

Future for the [`unconstrained`](unconstrained) method.

## tokio::task::coop::unconstrained::unconstrained (function)

Turn off cooperative scheduling for a future. The future will never be forced to yield by
Tokio. Using this exposes your service to starvation if the unconstrained future never yields
otherwise.

See also the usage example in the [task module](index.html#unconstrained).

## tokio::task::join_set::Builder (struct)

A variant of [`task::Builder`] that spawns tasks on a [`JoinSet`] rather
than on the current default runtime.

[`task::Builder`]: crate::task::Builder

## tokio::task::join_set::JoinSet (struct)

A collection of tasks spawned on a Tokio runtime.

A `JoinSet` can be used to await the completion of some or all of the tasks
in the set. The set is not ordered, and the tasks will be returned in the
order they complete.

All of the tasks must have the same return type `T`.

When the `JoinSet` is dropped, all tasks in the `JoinSet` are immediately aborted.

### tokio::task::join_set::JoinSet (struct) › Examples

Spawn multiple tasks and wait for them.

```
use tokio::task::JoinSet;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let mut set = JoinSet::new();

for i in 0..10 {
    set.spawn(async move { i });
}

let mut seen = [false; 10];
while let Some(res) = set.join_next().await {
    let idx = res.unwrap();
    seen[idx] = true;
}

for i in 0..10 {
    assert!(seen[i]);
}
# }
```

### tokio::task::join_set::JoinSet (struct) › Task ID guarantees

While a task is tracked in a `JoinSet`, that task's ID is unique relative
to all other running tasks in Tokio. For this purpose, tracking a task in a
`JoinSet` is equivalent to holding a [`JoinHandle`] to it. See the [task ID]
documentation for more info.

[`JoinHandle`]: crate::task::JoinHandle
[task ID]: crate::task::Id

## tokio::task::local::LocalEnterGuard (struct)

Context guard for `LocalSet`

## tokio::task::local::LocalSet (struct)

A set of tasks which are executed on the same thread.

In some cases, it is necessary to run one or more futures that do not
implement [`Send`] and thus are unsafe to send between threads. In these
cases, a [local task set] may be used to schedule one or more `!Send`
futures to run together on the same thread.

For example, the following code will not compile:

```rust,compile_fail
use std::rc::Rc;

#[tokio::main]
async fn main() {
    // `Rc` does not implement `Send`, and thus may not be sent between
    // threads safely.
    let nonsend_data = Rc::new("my nonsend data...");

    let nonsend_data = nonsend_data.clone();
    // Because the `async` block here moves `nonsend_data`, the future is `!Send`.
    // Since `tokio::spawn` requires the spawned future to implement `Send`, this
    // will not compile.
    tokio::spawn(async move {
        println!("{}", nonsend_data);
        // ...
    }).await.unwrap();
}
```

### tokio::task::local::LocalSet (struct) › Use with `run_until`

To spawn `!Send` futures, we can use a local task set to schedule them
on the thread calling [`Runtime::block_on`]. When running inside of the
local task set, we can use [`task::spawn_local`], which can spawn
`!Send` futures. For example:

```rust
use std::rc::Rc;
use tokio::task;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let nonsend_data = Rc::new("my nonsend data...");

// Construct a local task set that can run `!Send` futures.
let local = task::LocalSet::new();

// Run the local task set.
local.run_until(async move {
    let nonsend_data = nonsend_data.clone();
    // `spawn_local` ensures that the future is spawned on the local
    // task set.
    task::spawn_local(async move {
        println!("{}", nonsend_data);
        // ...
    }).await.unwrap();
}).await;
# }
```
**Note:** The `run_until` method can only be used in `#[tokio::main]`,
`#[tokio::test]` or directly inside a call to [`Runtime::block_on`]. It
cannot be used inside a task spawned with `tokio::spawn`.

### tokio::task::local::LocalSet (struct) › Awaiting a `LocalSet`

Additionally, a `LocalSet` itself implements `Future`, completing when
*all* tasks spawned on the `LocalSet` complete. This can be used to run
several futures on a `LocalSet` and drive the whole set until they
complete. For example,

```rust
use tokio::{task, time};
use std::rc::Rc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let nonsend_data = Rc::new("world");
let local = task::LocalSet::new();

let nonsend_data2 = nonsend_data.clone();
local.spawn_local(async move {
    // ...
    println!("hello {}", nonsend_data2)
});

local.spawn_local(async move {
    time::sleep(time::Duration::from_millis(100)).await;
    println!("goodbye {}", nonsend_data)
});

// ...

local.await;
# }
```
**Note:** Awaiting a `LocalSet` can only be done inside
`#[tokio::main]`, `#[tokio::test]` or directly inside a call to
[`Runtime::block_on`]. It cannot be used inside a task spawned with
`tokio::spawn`.

### tokio::task::local::LocalSet (struct) › Use inside `tokio::spawn`

The two methods mentioned above cannot be used inside `tokio::spawn`, so
to spawn `!Send` futures from inside `tokio::spawn`, we need to do
something else. The solution is to create the `LocalSet` somewhere else,
and communicate with it using an [`mpsc`] channel.

The following example puts the `LocalSet` inside a new thread.
```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime::Builder;
use tokio::sync::{mpsc, oneshot};
use tokio::task::LocalSet;

// This struct describes the task you want to spawn. Here we include
// some simple examples. The oneshot channel allows sending a response
// to the spawner.
#[derive(Debug)]
enum Task {
    PrintNumber(u32),
    AddOne(u32, oneshot::Sender<u32>),
}

#[derive(Clone)]
struct LocalSpawner {
   send: mpsc::UnboundedSender<Task>,
}

impl LocalSpawner {
    pub fn new() -> Self {
        let (send, mut recv) = mpsc::unbounded_channel();

        let rt = Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap();

        std::thread::spawn(move || {
            let local = LocalSet::new();

            local.spawn_local(async move {
                while let Some(new_task) = recv.recv().await {
                    tokio::task::spawn_local(run_task(new_task));
                }
                // If the while loop returns, then all the LocalSpawner
                // objects have been dropped.
            });

            // This will return once all senders are dropped and all
            // spawned tasks have returned.
            rt.block_on(local);
        });

        Self {
            send,
        }
    }

    pub fn spawn(&self, task: Task) {
        self.send.send(task).expect("Thread with LocalSet has shut down.");
    }
}

// This task may do !Send stuff. We use printing a number as an example,
// but it could be anything.
//
// The Task struct is an enum to support spawning many different kinds
// of operations.
async fn run_task(task: Task) {
    match task {
        Task::PrintNumber(n) => {
            println!("{}", n);
        },
        Task::AddOne(n, response) => {
            // We ignore failures to send the response.
            let _ = response.send(n + 1);
        },
    }
}

#[tokio::main]
async fn main() {
    let spawner = LocalSpawner::new();

    let (send, response) = oneshot::channel();
    spawner.spawn(Task::AddOne(10, send));
    let eleven = response.await.unwrap();
    assert_eq!(eleven, 11);
}
# }
```

[`Send`]: trait@std::marker::Send
[local task set]: struct@LocalSet
[`Runtime::block_on`]: method@crate::runtime::Runtime::block_on
[`task::spawn_local`]: fn@spawn_local
[`mpsc`]: mod@crate::sync::mpsc

## tokio::task::local::spawn_local (function)

Spawns a `!Send` future on the current [`LocalSet`] or [`LocalRuntime`].

This is possible when either using one of these types explicitly, or by
opting to use the `"local"` runtime flavor in `tokio::main`:

```ignore
#[tokio::main(flavor = "local")]
```

The spawned future will run on the same thread that called `spawn_local`.

The provided future will start running in the background immediately
when `spawn_local` is called, even if you don't await the returned
`JoinHandle`.

### tokio::task::local::spawn_local (function) › Panics

This function panics if called outside of a [`LocalSet`] or [`LocalRuntime`].

Note that if [`tokio::spawn`] is used from within a `LocalSet`, the
resulting new task will _not_ be inside the `LocalSet`, so you must use
`spawn_local` if you want to stay within the `LocalSet`.

### tokio::task::local::spawn_local (function) › Examples

With `LocalSet`:

```rust
use std::rc::Rc;
use tokio::task;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let nonsend_data = Rc::new("my nonsend data...");

let local = task::LocalSet::new();

// Run the local task set.
local.run_until(async move {
    let nonsend_data = nonsend_data.clone();
    task::spawn_local(async move {
        println!("{}", nonsend_data);
        // ...
    }).await.unwrap();
}).await;
# }
```
With local runtime flavor.

```rust
#[tokio::main(flavor = "local")]
async fn main() {
    let join = tokio::task::spawn_local(async {
        println!("my nonsend data...")
    });

   join.await.unwrap()
 }

```

[`LocalSet`]: struct@crate::task::LocalSet
[`LocalRuntime`]: struct@crate::runtime::LocalRuntime
[`tokio::spawn`]: fn@crate::task::spawn
[unstable]: ../../tokio/index.html#unstable-features

## tokio::task::spawn::spawn (function)

Spawns a new asynchronous task, returning a
[`JoinHandle`] for it.

The provided future will start running in the background immediately
when `spawn` is called, even if you don't await the returned
[`JoinHandle`].

Spawning a task enables the task to execute concurrently to other tasks. The
spawned task may execute on the current thread, or it may be sent to a
different thread to be executed. The specifics depend on the current
[`Runtime`](crate::runtime::Runtime) configuration. In a
[running runtime][running-runtime], the task will start immediately in the
background. On a blocked runtime, the user must drive the runtime forward (for
example, by calling [`Runtime::block_on`](crate::runtime::Runtime::block_on)).

It is guaranteed that spawn will not synchronously poll the task being spawned.
This means that calling spawn while holding a lock does not pose a risk of
deadlocking with the spawned task.

There is no guarantee that a spawned task will execute to completion.
When a runtime is shutdown, all outstanding tasks are dropped,
regardless of the lifecycle of that task.

This function must be called from the context of a Tokio runtime. Tasks running on
the Tokio runtime are always inside its context, but you can also enter the context
using the [`Runtime::enter`](crate::runtime::Runtime::enter()) method.

[running-runtime]: ../runtime/index.html#driving-the-runtime

### tokio::task::spawn::spawn (function) › Examples

In this example, a server is started and `spawn` is used to start a new task
that processes each received connection.

```no_run
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::net::{TcpListener, TcpStream};

use std::io;

async fn process(socket: TcpStream) {
    // ...
# drop(socket);
}

#[tokio::main]
async fn main() -> io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:8080").await?;

    loop {
        let (socket, _) = listener.accept().await?;

        tokio::spawn(async move {
            // Process each socket concurrently.
            process(socket).await
        });
    }
}
# }
```

To run multiple tasks in parallel and receive their results, join
handles can be stored in a vector.
```
# #[tokio::main(flavor = "current_thread")] async fn main() {
async fn my_background_op(id: i32) -> String {
    let s = format!("Starting background task {}.", id);
    println!("{}", s);
    s
}

let ops = vec![1, 2, 3];
let mut tasks = Vec::with_capacity(ops.len());
for op in ops {
    // This call will make them start running in the background
    // immediately.
    tasks.push(tokio::spawn(my_background_op(op)));
}

let mut outputs = Vec::with_capacity(tasks.len());
for task in tasks {
    outputs.push(task.await.unwrap());
}
println!("{:?}", outputs);
# }
```
This example pushes the tasks to `outputs` in the order they were
started in. If you do not care about the ordering of the outputs, then
you can also use a [`JoinSet`].

[`JoinSet`]: struct@crate::task::JoinSet

### tokio::task::spawn::spawn (function) › Panics

Panics if called from **outside** of the Tokio runtime.

### tokio::task::spawn::spawn (function) › Using `!Send` values from a task

The task supplied to `spawn` must implement `Send`. However, it is
possible to **use** `!Send` values from the task as long as they only
exist between calls to `.await`.

For example, this will work:

```
use tokio::task;

use std::rc::Rc;

fn use_rc(rc: Rc<()>) {
    // Do stuff w/ rc
# drop(rc);
}

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
tokio::spawn(async {
    // Force the `Rc` to stay in a scope with no `.await`
    {
        let rc = Rc::new(());
        use_rc(rc.clone());
    }

    task::yield_now().await;
}).await.unwrap();
# }
```

This will **not** work:

```compile_fail
use tokio::task;

use std::rc::Rc;

fn use_rc(rc: Rc<()>) {
    // Do stuff w/ rc
# drop(rc);
}

#[tokio::main]
async fn main() {
    tokio::spawn(async {
        let rc = Rc::new(());

        task::yield_now().await;

        use_rc(rc.clone());
    }).await.unwrap();
}
```

Holding on to a `!Send` value across calls to `.await` will result in
an unfriendly compile error message similar to:

```text
`[... some type ...]` cannot be sent between threads safely
```

or:

```text
error[E0391]: cycle detected when processing `main`
```

## tokio::task::task_local::AccessError (struct)

An error returned by [`LocalKey::try_with`](method@LocalKey::try_with).

## tokio::task::task_local::LocalKey (struct)

A key for task-local data.

This type is generated by the [`task_local!`] macro.

Unlike [`std::thread::LocalKey`], `tokio::task::LocalKey` will
_not_ lazily initialize the value on first access. Instead, the
value is first initialized when the future containing
the task-local is first polled by a futures executor, like Tokio.

### tokio::task::task_local::LocalKey (struct) › Examples

```
# async fn dox() {
tokio::task_local! {
    static NUMBER: u32;
}

NUMBER.scope(1, async move {
    assert_eq!(NUMBER.get(), 1);
}).await;

NUMBER.scope(2, async move {
    assert_eq!(NUMBER.get(), 2);

    NUMBER.scope(3, async move {
        assert_eq!(NUMBER.get(), 3);
    }).await;
}).await;
# }
```

[`std::thread::LocalKey`]: struct@std::thread::LocalKey
[`task_local!`]: ../macro.task_local.html

## tokio::task::task_local::TaskLocalFuture (struct)

A future that sets a value `T` of a task local for the future `F` during
its execution.

The value of the task-local must be `'static` and will be dropped on the
completion of the future.

Created by the function [`LocalKey::scope`](self::LocalKey::scope).

### tokio::task::task_local::TaskLocalFuture (struct) › Examples

```
# async fn dox() {
tokio::task_local! {
    static NUMBER: u32;
}

NUMBER.scope(1, async move {
    println!("task local value: {}", NUMBER.get());
}).await;
# }
```

## tokio::task::yield_now::yield_now (function)

Yields execution back to the Tokio runtime.

A task yields by awaiting on `yield_now()`, and may resume when that future
completes (with no output.) The current task will be re-added as a pending
task at the _back_ of the pending queue. Any other pending tasks will be
scheduled. No other waking is required for the task to continue.

See also the usage example in the [task module](index.html#yield_now).

### tokio::task::yield_now::yield_now (function) › Non-guarantees

This function may not yield all the way up to the executor if there are any
special combinators above it in the call stack. For example, if a
[`tokio::select!`] has another branch complete during the same poll as the
`yield_now()`, then the yield is not propagated all the way up to the
runtime.

It is generally not guaranteed that the runtime behaves like you expect it
to when deciding which task to schedule next after a call to `yield_now()`.
In particular, the runtime may choose to poll the task that just ran
`yield_now()` again immediately without polling any other tasks first. For
example, the runtime will not drive the IO driver between every poll of a
task, and this could result in the runtime polling the current task again
immediately even if there is another task that could make progress if that
other task is waiting for a notification from the IO driver.

In general, changes to the order in which the runtime polls tasks is not
considered a breaking change, and your program should be correct no matter
which order the runtime polls your tasks in.

[`tokio::select!`]: macro@crate::select

## tokio::task_local (macro)

Declares a new task-local key of type [`tokio::task::LocalKey`].

### tokio::task_local (macro) › Syntax

The macro wraps any number of static declarations and makes them local to the current task.
Publicity and attributes for each static is preserved. For example:

### tokio::task_local (macro) › Examples

```
# use tokio::task_local;
task_local! {
    pub static ONE: u32;

    #[allow(unused)]
    static TWO: f32;
}
# fn main() {}
```

See [`LocalKey` documentation][`tokio::task::LocalKey`] for more
information.

[`tokio::task::LocalKey`]: struct@crate::task::LocalKey

## tokio::tasks (function)

Tasks in this snapshot.

## tokio::tclass_v6 (function)

Gets the value of the `IPV6_TCLASS` option for this socket.

For more information about this option, see [`set_tclass_v6`].

[`set_tclass_v6`]: Self::set_tclass_v6

## tokio::tclass_v6 (function)

Gets the value of the `IPV6_TCLASS` option for this socket.

For more information about this option, see [`set_tclass_v6`].

[`set_tclass_v6`]: Self::set_tclass_v6

## tokio::terminate (function)

Represents the `SIGTERM` signal.

On Unix systems this signal is sent to issue a shutdown of the
process. By default, the process is terminated by this signal.

## tokio::thread_keep_alive (function)

Sets a custom timeout for a thread in the blocking pool.

By default, the timeout for a thread is set to 10 seconds. This can
be overridden using `.thread_keep_alive()`.

### tokio::thread_keep_alive (function) › Example

```
# #[cfg(not(target_family = "wasm"))]
# {
# use tokio::runtime;
# use std::time::Duration;
# pub fn main() {
let rt = runtime::Builder::new_multi_thread()
    .thread_keep_alive(Duration::from_millis(100))
    .build();
# }
# }
```

## tokio::thread_name (function)

Sets name of threads spawned by the `Runtime`'s thread pool.

The default name is "tokio-rt-worker".

### tokio::thread_name (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
# use tokio::runtime;

# pub fn main() {
let rt = runtime::Builder::new_multi_thread()
    .thread_name("my-pool")
    .build();
# }
# }
```

## tokio::thread_name_fn (function)

Sets a function used to generate the name of threads spawned by the `Runtime`'s thread pool.

The default name fn is `|| "tokio-rt-worker".into()`.

### tokio::thread_name_fn (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
# use tokio::runtime;
# use std::sync::atomic::{AtomicUsize, Ordering};
# pub fn main() {
let rt = runtime::Builder::new_multi_thread()
    .thread_name_fn(|| {
       static ATOMIC_ID: AtomicUsize = AtomicUsize::new(0);
       let id = ATOMIC_ID.fetch_add(1, Ordering::SeqCst);
       format!("my-pool-{}", id)
    })
    .build();
# }
# }
```

## tokio::thread_stack_size (function)

Sets the stack size (in bytes) for worker threads.

The actual stack size may be greater than this value if the platform
specifies minimal stack size.

The default stack size for spawned threads is 2 MiB, though this
particular stack size is subject to change in the future.

### tokio::thread_stack_size (function) › Examples

```
# #[cfg(not(target_family = "wasm"))]
# {
# use tokio::runtime;

# pub fn main() {
let rt = runtime::Builder::new_multi_thread()
    .thread_stack_size(32 * 1024)
    .build();
# }
# }
```

## tokio::tick (function)

Completes when the next instant in the interval has been reached.

### tokio::tick (function) › Cancel safety

This method is cancel safe. If `tick` is used as a branch in
[`tokio::select!`](crate::select) and another branch completes first,
then no tick has been consumed.

### tokio::tick (function) › Examples

```
use tokio::time;

use std::time::Duration;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let mut interval = time::interval(Duration::from_millis(10));

interval.tick().await;
// approximately 0ms have elapsed. The first tick completes immediately.
interval.tick().await;
interval.tick().await;

// approximately 20ms have elapsed.
# }
```

## tokio::time::clock::advance (function)

Advances time.

Increments the saved `Instant::now()` value by `duration`. Subsequent
calls to `Instant::now()` will return the result of the increment.

This function will make the current time jump forward by the given
duration in one jump. This means that all `sleep` calls with a deadline
before the new time will immediately complete "at the same time", and
the runtime is free to poll them in any order.  Additionally, this
method will not wait for the `sleep` calls it advanced past to complete.
If you want to do that, you should instead call [`sleep`] and rely on
the runtime's auto-advance feature.

Note that calls to `sleep` are not guaranteed to complete the first time
they are polled after a call to `advance`. For example, this can happen
if the runtime has not yet touched the timer driver after the call to
`advance`. However if they don't, the runtime will poll the task again
shortly.

### tokio::time::clock::advance (function) › When to use `sleep` instead

**Important:** `advance` is designed for testing scenarios where you want to
instantly jump forward in time. However, it has limitations that make it
unsuitable for certain use cases:

- **Forcing timeouts:** If you want to reliably trigger a timeout, prefer
  using [`sleep`] with auto-advance rather than `advance`. The `advance`
  function jumps time forward but doesn't guarantee that all timers will be
  processed before your code continues.

- **Simulating freezes:** If you're trying to simulate a scenario where the
  program freezes and then resumes, the batch behavior of `advance` may not
  produce the expected results. All timers that expire during the advance
  complete simultaneously.

For most testing scenarios where you want to wait for a duration to pass
and have all timers fire in order, use [`sleep`] instead:

```ignore
use tokio::time::{self, Duration};

#[tokio::test(start_paused = true)]
async fn test_timeout_reliable() {
    // Use sleep with auto-advance for reliable timeout testing
    time::sleep(Duration::from_secs(5)).await;
    // All timers that were scheduled to fire within 5 seconds
    // have now been processed in order
}
```

### tokio::time::clock::advance (function) › Panics

Panics if any of the following conditions are met:

- The clock is not frozen, which means that you must
  call [`pause`] before calling this method.
- If called outside of the Tokio runtime.
- If the input `duration` is too large (such as [`Duration::MAX`])
  to be safely added to the current time without causing an overflow.

### tokio::time::clock::advance (function) › Caveats

Using a very large `duration` is not recommended,
as it may cause panicking due to overflow.

### tokio::time::clock::advance (function) › Auto-advance

If the time is paused and there is no work to do, the runtime advances
time to the next timer. See [`pause`](pause#auto-advance) for more
details.

[`sleep`]: fn@crate::time::sleep

## tokio::time::clock::pause (function)

Pauses time.

The current value of `Instant::now()` is saved and all subsequent calls
to `Instant::now()` will return the saved value. The saved value can be
changed by [`advance`] or by the time auto-advancing once the runtime
has no work to do. This only affects the `Instant` type in Tokio, and
the `Instant` in std continues to work as normal.

Pausing time requires the `current_thread` Tokio runtime. This is the
default runtime used by `#[tokio::test]`. The runtime can be initialized
with time in a paused state using the `Builder::start_paused` method.

For cases where time is immediately paused, it is better to pause
the time using the `main` or `test` macro:
```
#[tokio::main(flavor = "current_thread", start_paused = true)]
async fn main() {
   println!("Hello world");
}
```

### tokio::time::clock::pause (function) › Panics

Panics if time is already frozen or if called from outside of a
`current_thread` Tokio runtime.

### tokio::time::clock::pause (function) › Auto-advance

If time is paused and the runtime has no work to do, the clock is
auto-advanced to the next pending timer. This means that [`Sleep`] or
other timer-backed primitives can cause the runtime to advance the
current time when awaited.

### tokio::time::clock::pause (function) › Preventing auto-advance

In some testing scenarios, you may want to keep the clock paused without
auto-advancing, even while waiting for I/O or other asynchronous operations.
This can be achieved by using [`spawn_blocking`] to wrap your I/O operations.

When a blocking task is running, the clock's auto-advance is temporarily
inhibited. This allows you to wait for I/O to complete while keeping the
paused clock stationary:

```ignore
use tokio::time::{Duration, Instant};
use tokio::task;

#[tokio::test(start_paused = true)]
async fn test_with_io() {
    let start = Instant::now();

    // The clock will NOT auto-advance while this blocking task runs
    let result = task::spawn_blocking(|| {
        // Perform I/O operations here
        std::thread::sleep(std::time::Duration::from_millis(10));
        42
    }).await.unwrap();

    // Time has not advanced
    assert_eq!(start.elapsed(), Duration::ZERO);
}
```

[`Sleep`]: crate::time::Sleep
[`advance`]: crate::time::advance
[`spawn_blocking`]: crate::task::spawn_blocking

## tokio::time::clock::resume (function)

Resumes time.

Clears the saved `Instant::now()` value. Subsequent calls to
`Instant::now()` will return the value returned by the system call.

### tokio::time::clock::resume (function) › Panics

Panics if time is not frozen or if called from outside of the Tokio
runtime.

## tokio::time::error::Elapsed (struct)

Errors returned by `Timeout`.

This error is returned when a timeout expires before the function was able
to finish.

## tokio::time::error::Error (struct)

Errors encountered by the timer implementation.

Currently, there are two different errors that can occur:

* `shutdown` occurs when a timer operation is attempted, but the timer
  instance has been dropped. In this case, the operation will never be able
  to complete and the `shutdown` error is returned. This is a permanent
  error, i.e., once this error is observed, timer operations will never
  succeed in the future.

* `at_capacity` occurs when a timer operation is attempted, but the timer
  instance is currently handling its maximum number of outstanding sleep instances.
  In this case, the operation is not able to be performed at the current
  moment, and `at_capacity` is returned. This is a transient error, i.e., at
  some point in the future, if the operation is attempted again, it might
  succeed. Callers that observe this error should attempt to [shed load]. One
  way to do this would be dropping the future that issued the timer operation.

[shed load]: https://en.wikipedia.org/wiki/Load_Shedding

## tokio::time::instant::Instant (struct)

A measurement of a monotonically nondecreasing clock.
Opaque and useful only with `Duration`.

Instants are always guaranteed to be no less than any previously measured
instant when created, and are often useful for tasks such as measuring
benchmarks or timing how long an operation takes.

Note, however, that instants are not guaranteed to be **steady**. In other
words, each tick of the underlying clock may not be the same length (e.g.
some seconds may be longer than others). An instant may jump forwards or
experience time dilation (slow down or speed up), but it will never go
backwards.

Instants are opaque types that can only be compared to one another. There is
no method to get "the number of seconds" from an instant. Instead, it only
allows measuring the duration between two instants (or comparing two
instants).

The size of an `Instant` struct may vary depending on the target operating
system.

### tokio::time::instant::Instant (struct) › Note

This type wraps the inner `std` variant and is used to align the Tokio
clock for uses of `now()`. This can be useful for testing where you can
take advantage of `time::pause()` and `time::advance()`.

## tokio::time::interval::Interval (struct)

Interval returned by [`interval`] and [`interval_at`].

This type allows you to wait on a sequence of instants with a certain
duration between each instant. Unlike calling [`sleep`] in a loop, this lets
you count the time spent between the calls to [`sleep`] as well.

An `Interval` can be turned into a `Stream` with [`IntervalStream`].

[`IntervalStream`]: https://docs.rs/tokio-stream/latest/tokio_stream/wrappers/struct.IntervalStream.html
[`sleep`]: crate::time::sleep()

## tokio::time::interval::MissedTickBehavior (enum)

Defines the behavior of an [`Interval`] when it misses a tick.

Sometimes, an [`Interval`]'s tick is missed. For example, consider the
following:

```
use tokio::time::{self, Duration};
# async fn task_that_takes_one_to_three_millis() {}

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
// ticks every 2 milliseconds
let mut interval = time::interval(Duration::from_millis(2));
for _ in 0..5 {
    interval.tick().await;
    // if this takes more than 2 milliseconds, a tick will be delayed
    task_that_takes_one_to_three_millis().await;
}
# }
```

Generally, a tick is missed if too much time is spent without calling
[`Interval::tick()`].

By default, when a tick is missed, [`Interval`] fires ticks as quickly as it
can until it is "caught up" in time to where it should be.
`MissedTickBehavior` can be used to specify a different behavior for
[`Interval`] to exhibit. Each variant represents a different strategy.

Note that because the executor cannot guarantee exact precision with timers,
these strategies will only apply when the delay is greater than 5
milliseconds.

## tokio::time::interval::MissedTickBehavior::Burst (variant)

Ticks as fast as possible until caught up.

When this strategy is used, [`Interval`] schedules ticks "normally" (the
same as it would have if the ticks hadn't been delayed), which results
in it firing ticks as fast as possible until it is caught up in time to
where it should be. Unlike [`Delay`] and [`Skip`], the ticks yielded
when `Burst` is used (the [`Instant`]s that [`tick`](Interval::tick)
yields) aren't different than they would have been if a tick had not
been missed. Like [`Skip`], and unlike [`Delay`], the ticks may be
shortened.

This looks something like this:
```text
Expected ticks: |     1     |     2     |     3     |     4     |     5     |     6     |
Actual ticks:   | work -----|          delay          | work | work | work -| work -----|
```

In code:

```
use tokio::time::{interval, Duration};
# async fn task_that_takes_200_millis() {}

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let mut interval = interval(Duration::from_millis(50));

// First tick resolves immediately after creation
interval.tick().await;

task_that_takes_200_millis().await;
// The `Interval` has missed a tick

// Since we have exceeded our timeout, this will resolve immediately
interval.tick().await;

// Since we are more than 100ms after the start of `interval`, this will
// also resolve immediately.
interval.tick().await;

// Also resolves immediately, because it was supposed to resolve at
// 150ms after the start of `interval`
interval.tick().await;

// Resolves immediately
interval.tick().await;

// Since we have gotten to 200ms after the start of `interval`, this
// will resolve after 50ms
interval.tick().await;
# }
```

This is the default behavior when [`Interval`] is created with
[`interval`] and [`interval_at`].

[`Delay`]: MissedTickBehavior::Delay
[`Skip`]: MissedTickBehavior::Skip

## tokio::time::interval::MissedTickBehavior::Delay (variant)

Tick at multiples of `period` from when [`tick`] was called, rather than
from `start`.

When this strategy is used and [`Interval`] has missed a tick, instead
of scheduling ticks to fire at multiples of `period` from `start` (the
time when the first tick was fired), it schedules all future ticks to
happen at a regular `period` from the point when [`tick`] was called.
Unlike [`Burst`] and [`Skip`], ticks are not shortened, and they aren't
guaranteed to happen at a multiple of `period` from `start` any longer.

This looks something like this:
```text
Expected ticks: |     1     |     2     |     3     |     4     |     5     |     6     |
Actual ticks:   | work -----|          delay          | work -----| work -----| work -----|
```

In code:

```
use tokio::time::{interval, Duration, MissedTickBehavior};
# async fn task_that_takes_more_than_50_millis() {}

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let mut interval = interval(Duration::from_millis(50));
interval.set_missed_tick_behavior(MissedTickBehavior::Delay);

task_that_takes_more_than_50_millis().await;
// The `Interval` has missed a tick

// Since we have exceeded our timeout, this will resolve immediately
interval.tick().await;

// But this one, rather than also resolving immediately, as might happen
// with the `Burst` or `Skip` behaviors, will not resolve until
// 50ms after the call to `tick` up above. That is, in `tick`, when we
// recognize that we missed a tick, we schedule the next tick to happen
// 50ms (or whatever the `period` is) from right then, not from when
// were *supposed* to tick
interval.tick().await;
# }
```

[`Burst`]: MissedTickBehavior::Burst
[`Skip`]: MissedTickBehavior::Skip
[`tick`]: Interval::tick

## tokio::time::interval::MissedTickBehavior::Skip (variant)

Skips missed ticks and tick on the next multiple of `period` from
`start`.

When this strategy is used, [`Interval`] schedules the next tick to fire
at the next-closest tick that is a multiple of `period` away from
`start` (the point where [`Interval`] first ticked). Like [`Burst`], all
ticks remain multiples of `period` away from `start`, but unlike
[`Burst`], the ticks may not be *one* multiple of `period` away from the
last tick. Like [`Delay`], the ticks are no longer the same as they
would have been if ticks had not been missed, but unlike [`Delay`], and
like [`Burst`], the ticks may be shortened to be less than one `period`
away from each other.

This looks something like this:
```text
Expected ticks: |     1     |     2     |     3     |     4     |     5     |     6     |
Actual ticks:   | work -----|          delay          | work ---| work -----| work -----|
```

In code:

```
use tokio::time::{interval, Duration, MissedTickBehavior};
# async fn task_that_takes_75_millis() {}

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let mut interval = interval(Duration::from_millis(50));
interval.set_missed_tick_behavior(MissedTickBehavior::Skip);

task_that_takes_75_millis().await;
// The `Interval` has missed a tick

// Since we have exceeded our timeout, this will resolve immediately
interval.tick().await;

// This one will resolve after 25ms, 100ms after the start of
// `interval`, which is the closest multiple of `period` from the start
// of `interval` after the call to `tick` up above.
interval.tick().await;
# }
```

[`Burst`]: MissedTickBehavior::Burst
[`Delay`]: MissedTickBehavior::Delay

## tokio::time::interval::interval (function)

Creates new [`Interval`] that yields with interval of `period`. The first
tick completes immediately. The default [`MissedTickBehavior`] is
[`Burst`](MissedTickBehavior::Burst), but this can be configured
by calling [`set_missed_tick_behavior`](Interval::set_missed_tick_behavior).

An interval will tick indefinitely. At any time, the [`Interval`] value can
be dropped. This cancels the interval.

This function is equivalent to
[`interval_at(Instant::now(), period)`](interval_at).

### tokio::time::interval::interval (function) › Panics

This function panics if `period` is zero.

### tokio::time::interval::interval (function) › Examples

```
use tokio::time::{self, Duration};

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let mut interval = time::interval(Duration::from_millis(10));

interval.tick().await; // ticks immediately
interval.tick().await; // ticks after 10ms
interval.tick().await; // ticks after 10ms

// approximately 20ms have elapsed.
# }
```

A simple example using `interval` to execute a task every two seconds.

The difference between `interval` and [`sleep`] is that an [`Interval`]
measures the time since the last tick, which means that [`.tick().await`]
may wait for a shorter time than the duration specified for the interval
if some time has passed between calls to [`.tick().await`].

If the tick in the example below was replaced with [`sleep`], the task
would only be executed once every three seconds, and not every two
seconds.

```
use tokio::time;

async fn task_that_takes_a_second() {
    println!("hello");
    time::sleep(time::Duration::from_secs(1)).await
}

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let mut interval = time::interval(time::Duration::from_secs(2));
for _i in 0..5 {
    interval.tick().await;
    task_that_takes_a_second().await;
}
# }
```

[`sleep`]: crate::time::sleep()
[`.tick().await`]: Interval::tick

## tokio::time::interval::interval_at (function)

Creates new [`Interval`] that yields with interval of `period` with the
first tick completing at `start`. The default [`MissedTickBehavior`] is
[`Burst`](MissedTickBehavior::Burst), but this can be configured
by calling [`set_missed_tick_behavior`](Interval::set_missed_tick_behavior).

An interval will tick indefinitely. At any time, the [`Interval`] value can
be dropped. This cancels the interval.

### tokio::time::interval::interval_at (function) › Panics

This function panics if `period` is zero.

### tokio::time::interval::interval_at (function) › Examples

```
use tokio::time::{interval_at, Duration, Instant};

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let start = Instant::now() + Duration::from_millis(50);
let mut interval = interval_at(start, Duration::from_millis(10));

interval.tick().await; // ticks after 50ms
interval.tick().await; // ticks after 10ms
interval.tick().await; // ticks after 10ms

// approximately 70ms have elapsed.
# }
```

## tokio::time::sleep::Sleep (struct)

Future returned by [`sleep`](sleep) and [`sleep_until`](sleep_until).

This type does not implement the `Unpin` trait, which means that if you
use it with [`select!`] or by calling `poll`, you have to pin it first.
If you use it with `.await`, this does not apply.

### tokio::time::sleep::Sleep (struct) › Examples

Wait 100ms and print "100 ms have elapsed".

```
use tokio::time::{sleep, Duration};

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
sleep(Duration::from_millis(100)).await;
println!("100 ms have elapsed");
# }
```

Use with [`select!`]. Pinning the `Sleep` with [`tokio::pin!`] is
necessary when the same `Sleep` is selected on multiple times.
```no_run
use tokio::time::{self, Duration, Instant};

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let sleep = time::sleep(Duration::from_millis(10));
tokio::pin!(sleep);

loop {
    tokio::select! {
        () = &mut sleep => {
            println!("timer elapsed");
            sleep.as_mut().reset(Instant::now() + Duration::from_millis(50));
        },
    }
}
# }
```
Use in a struct with boxing. By pinning the `Sleep` with a `Box`, the
`HasSleep` struct implements `Unpin`, even though `Sleep` does not.
```
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::time::Sleep;

struct HasSleep {
    sleep: Pin<Box<Sleep>>,
}

impl Future for HasSleep {
    type Output = ();

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
        self.sleep.as_mut().poll(cx)
    }
}
```
Use in a struct with pin projection. This method avoids the `Box`, but
the `HasSleep` struct will not be `Unpin` as a consequence.
```
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::time::Sleep;
use pin_project_lite::pin_project;

pin_project! {
    struct HasSleep {
        #[pin]
        sleep: Sleep,
    }
}

impl Future for HasSleep {
    type Output = ();

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
        self.project().sleep.poll(cx)
    }
}
```

[`select!`]: ../macro.select.html
[`tokio::pin!`]: ../macro.pin.html

## tokio::time::sleep::sleep (function)

Waits until `duration` has elapsed.

Equivalent to `sleep_until(Instant::now() + duration)`. An asynchronous
analog to `std::thread::sleep`.

No work is performed while awaiting on the sleep future to complete. `Sleep`
operates at millisecond granularity and should not be used for tasks that
require high-resolution timers. The implementation is platform specific,
and some platforms (specifically Windows) will provide timers with a
larger resolution than 1 ms.

To run something regularly on a schedule, see [`interval`].

### tokio::time::sleep::sleep (function) › Cancellation

Canceling a sleep instance is done by dropping the returned future. No additional
cleanup work is required.

### tokio::time::sleep::sleep (function) › Examples

Wait 100ms and print "100 ms have elapsed".

```
use tokio::time::{sleep, Duration};

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
sleep(Duration::from_millis(100)).await;
println!("100 ms have elapsed");
# }
```

See the documentation for the [`Sleep`] type for more examples.

### tokio::time::sleep::sleep (function) › Panics

This function panics if there is no current timer set.

It can be triggered when [`Builder::enable_time`] or
[`Builder::enable_all`] are not included in the builder.

It can also panic whenever a timer is created outside of a
Tokio runtime. That is why `rt.block_on(sleep(...))` will panic,
since the function is executed outside of the runtime.
Whereas `rt.block_on(async {sleep(...).await})` doesn't panic.
And this is because wrapping the function on an async makes it lazy,
and so gets executed inside the runtime successfully without
panicking.

[`Sleep`]: struct@crate::time::Sleep
[`interval`]: crate::time::interval()
[`Builder::enable_time`]: crate::runtime::Builder::enable_time
[`Builder::enable_all`]: crate::runtime::Builder::enable_all

## tokio::time::sleep::sleep_until (function)

Waits until `deadline` is reached.

No work is performed while awaiting on the sleep future to complete. `Sleep`
operates at millisecond granularity and should not be used for tasks that
require high-resolution timers.

To run something regularly on a schedule, see [`interval`].

### tokio::time::sleep::sleep_until (function) › Cancellation

Canceling a sleep instance is done by dropping the returned future. No additional
cleanup work is required.

### tokio::time::sleep::sleep_until (function) › Examples

Wait 100ms and print "100 ms have elapsed".

```
use tokio::time::{sleep_until, Instant, Duration};

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
sleep_until(Instant::now() + Duration::from_millis(100)).await;
println!("100 ms have elapsed");
# }
```

See the documentation for the [`Sleep`] type for more examples.

### tokio::time::sleep::sleep_until (function) › Panics

This function panics if there is no current timer set.

It can be triggered when [`Builder::enable_time`] or
[`Builder::enable_all`] are not included in the builder.

It can also panic whenever a timer is created outside of a
Tokio runtime. That is why `rt.block_on(sleep(...))` will panic,
since the function is executed outside of the runtime.
Whereas `rt.block_on(async {sleep(...).await})` doesn't panic.
And this is because wrapping the function on an async makes it lazy,
and so gets executed inside the runtime successfully without
panicking.

[`Sleep`]: struct@crate::time::Sleep
[`interval`]: crate::time::interval()
[`Builder::enable_time`]: crate::runtime::Builder::enable_time
[`Builder::enable_all`]: crate::runtime::Builder::enable_all

## tokio::time::timeout::Timeout (struct)

Future returned by [`timeout`](timeout) and [`timeout_at`](timeout_at).

## tokio::time::timeout::timeout (function)

Requires a `Future` to complete before the specified duration has elapsed.

If the future completes before the duration has elapsed, then the completed
value is returned. Otherwise, an error is returned and the future is
canceled.

Note that the future is polled before the timeout is checked, so if the future
does not yield during execution then it is possible for the future to complete
and exceed the timeout _without_ returning an error.

This function returns a future whose return type is [`Result`]`<T,`[`Elapsed`]`>`, where `T` is the
return type of the provided future.

If the provided future completes immediately, then the future returned from
this function is guaranteed to complete immediately with an [`Ok`] variant
no matter the provided duration.

[`Ok`]: std::result::Result::Ok
[`Result`]: std::result::Result
[`Elapsed`]: crate::time::error::Elapsed

### tokio::time::timeout::timeout (function) › Cancellation

Cancelling a timeout is done by dropping the future. No additional cleanup
or other work is required.

The original future may be obtained by calling [`Timeout::into_inner`]. This
consumes the `Timeout`.

### tokio::time::timeout::timeout (function) › Examples

Create a new `Timeout` set to expire in 10 milliseconds.

```rust
use tokio::time::timeout;
use tokio::sync::oneshot;

use std::time::Duration;

# async fn dox() {
let (tx, rx) = oneshot::channel();
# tx.send(()).unwrap();

// Wrap the future with a `Timeout` set to expire in 10 milliseconds.
if let Err(_) = timeout(Duration::from_millis(10), rx).await {
    println!("did not receive value within 10 ms");
}
# }
```

### tokio::time::timeout::timeout (function) › Panics

This function panics if there is no current timer set.

It can be triggered when [`Builder::enable_time`] or
[`Builder::enable_all`] are not included in the builder.

It can also panic whenever a timer is created outside of a
Tokio runtime. That is why `rt.block_on(sleep(...))` will panic,
since the function is executed outside of the runtime.
Whereas `rt.block_on(async {sleep(...).await})` doesn't panic.
And this is because wrapping the function on an async makes it lazy,
and so gets executed inside the runtime successfully without
panicking.

[`Builder::enable_time`]: crate::runtime::Builder::enable_time
[`Builder::enable_all`]: crate::runtime::Builder::enable_all

## tokio::time::timeout::timeout_at (function)

Requires a `Future` to complete before the specified instant in time.

If the future completes before the instant is reached, then the completed
value is returned. Otherwise, an error is returned.

This function returns a future whose return type is [`Result`]`<T,`[`Elapsed`]`>`, where `T` is the
return type of the provided future.

If the provided future completes immediately, then the future returned from
this function is guaranteed to complete immediately with an [`Ok`] variant
no matter the provided deadline.

[`Ok`]: std::result::Result::Ok
[`Result`]: std::result::Result
[`Elapsed`]: crate::time::error::Elapsed

### tokio::time::timeout::timeout_at (function) › Cancellation

Cancelling a timeout is done by dropping the future. No additional cleanup
or other work is required.

The original future may be obtained by calling [`Timeout::into_inner`]. This
consumes the `Timeout`.

### tokio::time::timeout::timeout_at (function) › Examples

Create a new `Timeout` set to expire in 10 milliseconds.

```rust
use tokio::time::{Instant, timeout_at};
use tokio::sync::oneshot;

use std::time::Duration;

# async fn dox() {
let (tx, rx) = oneshot::channel();
# tx.send(()).unwrap();

// Wrap the future with a `Timeout` set to expire 10 milliseconds into the
// future.
if let Err(_) = timeout_at(Instant::now() + Duration::from_millis(10), rx).await {
    println!("did not receive value within 10 ms");
}
# }
```

### tokio::time::timeout::timeout_at (function) › Panics

This function panics if there is no current timer set.

It can be triggered when [`Builder::enable_time`] or
[`Builder::enable_all`] are not included in the builder.

It can also panic whenever a timer is created outside of a
Tokio runtime. That is why `rt.block_on(sleep(...))` will panic,
since the function is executed outside of the runtime.
Whereas `rt.block_on(async {sleep(...).await})` doesn't panic.
And this is because wrapping the function on an async makes it lazy,
and so gets executed inside the runtime successfully without
panicking.

[`Builder::enable_time`]: crate::runtime::Builder::enable_time
[`Builder::enable_all`]: crate::runtime::Builder::enable_all

## tokio::tos_v4 (function)

Gets the value of the `IP_TOS` option for this socket.

For more information about this option, see [`set_tos_v4`].

[`set_tos_v4`]: Self::set_tos_v4

## tokio::tos_v4 (function)

Gets the value of the `IP_TOS` option for this socket.

For more information about this option, see [`set_tos_v4`].

[`set_tos_v4`]: Self::set_tos_v4

## tokio::trace (function)

A trace of this task's state.

## tokio::trace_leaf_addr (struct_field)

The address of the internal `trace_leaf` function that triggered this callback.

When capturing a backtrace, use this as the lower bound — frames at or below
this address are internal implementation details and should be excluded.

## tokio::truncate (function)

Sets the option for truncating a previous file.

If a file is successfully opened with this option set it will truncate
the file to 0 length if it already exists.

The file must be opened with write access for truncate to work.

This is an async version of [`std::fs::OpenOptions::truncate`][std]

[std]: std::fs::OpenOptions::truncate

### tokio::truncate (function) › Examples

```no_run
use tokio::fs::OpenOptions;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let file = OpenOptions::new()
        .write(true)
        .truncate(true)
        .open("foo.txt")
        .await?;

    Ok(())
}
```

## tokio::try_acquire (function)

Tries to acquire a permit from the semaphore.

If the semaphore has been closed, this returns a [`TryAcquireError::Closed`]
and a [`TryAcquireError::NoPermits`] if there are no permits left. Otherwise,
this returns a [`SemaphorePermit`] representing the acquired permits.

### tokio::try_acquire (function) › Examples

```
use tokio::sync::{Semaphore, TryAcquireError};

# fn main() {
let semaphore = Semaphore::new(2);

let permit_1 = semaphore.try_acquire().unwrap();
assert_eq!(semaphore.available_permits(), 1);

let permit_2 = semaphore.try_acquire().unwrap();
assert_eq!(semaphore.available_permits(), 0);

let permit_3 = semaphore.try_acquire();
assert_eq!(permit_3.err(), Some(TryAcquireError::NoPermits));
# }
```

[`TryAcquireError::Closed`]: crate::sync::TryAcquireError::Closed
[`TryAcquireError::NoPermits`]: crate::sync::TryAcquireError::NoPermits
[`SemaphorePermit`]: crate::sync::SemaphorePermit

## tokio::try_acquire_many (function)

Tries to acquire `n` permits from the semaphore.

If the semaphore has been closed, this returns a [`TryAcquireError::Closed`]
and a [`TryAcquireError::NoPermits`] if there are not enough permits left.
Otherwise, this returns a [`SemaphorePermit`] representing the acquired permits.

### tokio::try_acquire_many (function) › Examples

```
use tokio::sync::{Semaphore, TryAcquireError};

# fn main() {
let semaphore = Semaphore::new(4);

let permit_1 = semaphore.try_acquire_many(3).unwrap();
assert_eq!(semaphore.available_permits(), 1);

let permit_2 = semaphore.try_acquire_many(2);
assert_eq!(permit_2.err(), Some(TryAcquireError::NoPermits));
# }
```

[`TryAcquireError::Closed`]: crate::sync::TryAcquireError::Closed
[`TryAcquireError::NoPermits`]: crate::sync::TryAcquireError::NoPermits
[`SemaphorePermit`]: crate::sync::SemaphorePermit

## tokio::try_acquire_many_owned (function)

Tries to acquire `n` permits from the semaphore.

The semaphore must be wrapped in an [`Arc`] to call this method. If
the semaphore has been closed, this returns a [`TryAcquireError::Closed`]
and a [`TryAcquireError::NoPermits`] if there are no permits left.
Otherwise, this returns a [`OwnedSemaphorePermit`] representing the
acquired permit.

### tokio::try_acquire_many_owned (function) › Examples

```
use std::sync::Arc;
use tokio::sync::{Semaphore, TryAcquireError};

# fn main() {
let semaphore = Arc::new(Semaphore::new(4));

let permit_1 = Arc::clone(&semaphore).try_acquire_many_owned(3).unwrap();
assert_eq!(semaphore.available_permits(), 1);

let permit_2 = semaphore.try_acquire_many_owned(2);
assert_eq!(permit_2.err(), Some(TryAcquireError::NoPermits));
# }
```

[`Arc`]: std::sync::Arc
[`TryAcquireError::Closed`]: crate::sync::TryAcquireError::Closed
[`TryAcquireError::NoPermits`]: crate::sync::TryAcquireError::NoPermits
[`OwnedSemaphorePermit`]: crate::sync::OwnedSemaphorePermit

## tokio::try_acquire_owned (function)

Tries to acquire a permit from the semaphore.

The semaphore must be wrapped in an [`Arc`] to call this method. If
the semaphore has been closed, this returns a [`TryAcquireError::Closed`]
and a [`TryAcquireError::NoPermits`] if there are no permits left.
Otherwise, this returns a [`OwnedSemaphorePermit`] representing the
acquired permit.

### tokio::try_acquire_owned (function) › Examples

```
use std::sync::Arc;
use tokio::sync::{Semaphore, TryAcquireError};

# fn main() {
let semaphore = Arc::new(Semaphore::new(2));

let permit_1 = Arc::clone(&semaphore).try_acquire_owned().unwrap();
assert_eq!(semaphore.available_permits(), 1);

let permit_2 = Arc::clone(&semaphore).try_acquire_owned().unwrap();
assert_eq!(semaphore.available_permits(), 0);

let permit_3 = semaphore.try_acquire_owned();
assert_eq!(permit_3.err(), Some(TryAcquireError::NoPermits));
# }
```

[`Arc`]: std::sync::Arc
[`TryAcquireError::Closed`]: crate::sync::TryAcquireError::Closed
[`TryAcquireError::NoPermits`]: crate::sync::TryAcquireError::NoPermits
[`OwnedSemaphorePermit`]: crate::sync::OwnedSemaphorePermit

## tokio::try_clone (function)

Creates a new `File` instance that shares the same underlying file handle
as the existing `File` instance. Reads, writes, and seeks will affect both
File instances simultaneously.

### tokio::try_clone (function) › Examples

```no_run
use tokio::fs::File;

# async fn dox() -> std::io::Result<()> {
let file = File::open("foo.txt").await?;
let file_clone = file.try_clone().await?;
# Ok(())
# }
```

## tokio::try_current (function)

Returns a Handle view over the currently running Runtime

Returns an error if no Runtime has been started

Contrary to `current`, this never panics

## tokio::try_downgrade_map (function)

Attempts to make a new [`OwnedRwLockReadGuard`] for a component of
the locked data. The original guard is returned if the closure returns
`None`.

This operation cannot fail as the `OwnedRwLockWriteGuard` passed in already
locked the data.

This is an associated function that needs to be
used as `OwnedRwLockWriteGuard::try_downgrade_map(...)`. A method would interfere with
methods of the same name on the contents of the locked data.

Inside of `f`, you retain exclusive access to the data, despite only being given a `&T`. Handing out a
`&mut T` would result in unsoundness, as you could use interior mutability.

If this function returns `Err(...)`, the lock is never unlocked nor downgraded.

### tokio::try_downgrade_map (function) › Examples

```
use std::sync::Arc;
use tokio::sync::{RwLock, OwnedRwLockWriteGuard};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Foo(u32);

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let lock = Arc::new(RwLock::new(Foo(1)));

let guard = Arc::clone(&lock).write_owned().await;
let guard = OwnedRwLockWriteGuard::try_downgrade_map(guard, |f| Some(&f.0)).expect("should not fail");
let foo = lock.read_owned().await;
assert_eq!(foo.0, *guard);
# }
```

## tokio::try_downgrade_map (function)

Attempts to make a new [`RwLockReadGuard`] for a component of
the locked data. The original guard is returned if the closure returns
`None`.

This operation cannot fail as the `RwLockWriteGuard` passed in already
locked the data.

This is an associated function that needs to be
used as `RwLockWriteGuard::try_downgrade_map(...)`. A method would interfere with
methods of the same name on the contents of the locked data.

This is equivalent to a combination of asynchronous [`RwLockWriteGuard::try_map`] and [`RwLockWriteGuard::downgrade`]
from the [`parking_lot` crate].

Inside of `f`, you retain exclusive access to the data, despite only being given a `&T`. Handing out a
`&mut T` would result in unsoundness, as you could use interior mutability.

If this function returns `Err(...)`, the lock is never unlocked nor downgraded.

[`RwLockMappedWriteGuard`]: struct@crate::sync::RwLockMappedWriteGuard
[`RwLockWriteGuard::map`]: https://docs.rs/lock_api/latest/lock_api/struct.RwLockWriteGuard.html#method.map
[`RwLockWriteGuard::downgrade`]: https://docs.rs/lock_api/latest/lock_api/struct.RwLockWriteGuard.html#method.downgrade
[`parking_lot` crate]: https://crates.io/crates/parking_lot

### tokio::try_downgrade_map (function) › Examples

```
use tokio::sync::{RwLock, RwLockWriteGuard};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Foo(u32);

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let lock = RwLock::new(Foo(1));

let guard = RwLockWriteGuard::try_downgrade_map(lock.write().await, |f| Some(&f.0)).expect("should not fail");
let foo = lock.read().await;
assert_eq!(foo.0, *guard);
# }
```

## tokio::try_from (function)

Consumes stream, returning the tokio I/O object.

This is equivalent to
[`TcpListener::from_std(stream)`](TcpListener::from_std).

## tokio::try_from (function)

Consumes stream, returning the tokio I/O object.

This is equivalent to
[`TcpStream::from_std(stream)`](TcpStream::from_std).

## tokio::try_from (function)

Consumes stream, returning the tokio I/O object.

This is equivalent to
[`UdpSocket::from_std(stream)`](UdpSocket::from_std).

## tokio::try_from (function)

Consumes stream, returning the tokio I/O object.

This is equivalent to
[`UnixListener::from_std(stream)`](UnixListener::from_std).

## tokio::try_from (function)

Consumes stream, returning the tokio I/O object.

This is equivalent to
[`UnixStream::from_std(stream)`](UnixStream::from_std).

## tokio::try_get (function)

Returns a copy of the task-local value
if the task-local value implements `Clone`.

If the task-local with the associated key is not present, this
method will return an `AccessError`. For a panicking variant,
see `get`.

## tokio::try_into_panic (function)

Consumes the join error, returning the object with which the task
panicked if the task terminated due to a panic. Otherwise, `self` is
returned.

### tokio::try_into_panic (function) › Examples

```should_panic,ignore-wasm
use std::panic;

#[tokio::main]
async fn main() {
    let err = tokio::spawn(async {
        panic!("boom");
    }).await.unwrap_err();

    if let Ok(reason) = err.try_into_panic() {
        // Resume the panic on the main task
        panic::resume_unwind(reason);
    }
}
```

## tokio::try_into_std (function)

Tries to immediately destructure `File` into a [`std::fs::File`].

### tokio::try_into_std (function) › Errors

This function will return an error containing the file if some
operation is in-flight.

### tokio::try_into_std (function) › Examples

```no_run
use tokio::fs::File;

# async fn dox() -> std::io::Result<()> {
let tokio_file = File::open("foo.txt").await?;
let std_file = tokio_file.try_into_std().unwrap();
# Ok(())
# }
```

## tokio::try_io (function)

Performs the provided IO operation.

If `f` returns a [`WouldBlock`] error, the readiness state associated
with this file descriptor is cleared, and the method returns
`Err(TryIoError::WouldBlock)`. You will typically need to poll the
`AsyncFd` again when this happens.

This method helps ensure that the readiness state of the underlying file
descriptor remains in sync with the tokio-side readiness state, by
clearing the tokio-side state only when a [`WouldBlock`] condition
occurs. It is the responsibility of the caller to ensure that `f`
returns [`WouldBlock`] only if the file descriptor that originated this
`AsyncFdReadyGuard` no longer expresses the readiness state that was queried to
create this `AsyncFdReadyGuard`.

### tokio::try_io (function) › Examples

This example sends some bytes to the inner [`std::net::UdpSocket`]. Waiting
for write-readiness and retrying when the send operation does block are explicit.
This example can be written more succinctly using [`AsyncFd::async_io`].

```no_run
use tokio::io::unix::AsyncFd;

use std::io;
use std::net::UdpSocket;

#[tokio::main]
async fn main() -> io::Result<()> {
    let socket = UdpSocket::bind("0.0.0.0:8080")?;
    socket.set_nonblocking(true)?;
    let async_fd = AsyncFd::new(socket)?;

    let written = loop {
        let mut guard = async_fd.writable().await?;
        match guard.try_io(|inner| inner.get_ref().send(&[1, 2])) {
            Ok(result) => {
                break result?;
            }
            Err(_would_block) => {
                // try_io already cleared the file descriptor's readiness state
                continue;
            }
        }
    };

    println!("wrote {written} bytes");

    Ok(())
}
```

[`WouldBlock`]: std::io::ErrorKind::WouldBlock

## tokio::try_io (function)

Performs the provided IO operation.

If `f` returns a [`WouldBlock`] error, the readiness state associated
with this file descriptor is cleared, and the method returns
`Err(TryIoError::WouldBlock)`. You will typically need to poll the
`AsyncFd` again when this happens.

This method helps ensure that the readiness state of the underlying file
descriptor remains in sync with the tokio-side readiness state, by
clearing the tokio-side state only when a [`WouldBlock`] condition
occurs. It is the responsibility of the caller to ensure that `f`
returns [`WouldBlock`] only if the file descriptor that originated this
`AsyncFdReadyGuard` no longer expresses the readiness state that was queried to
create this `AsyncFdReadyGuard`.

[`WouldBlock`]: std::io::ErrorKind::WouldBlock

## tokio::try_io (function)

Tries to read or write from the file descriptor using a user-provided IO operation.

If the file descriptor is ready, the provided closure is called. The closure
should attempt to perform IO operation on the file descriptor by manually
calling the appropriate syscall. If the operation fails because the
file descriptor is not actually ready, then the closure should return a
`WouldBlock` error and the readiness flag is cleared. The return value
of the closure is then returned by `try_io`.

If the file descriptor is not ready, then the closure is not called
and a `WouldBlock` error is returned.

The closure should only return a `WouldBlock` error if it has performed
an IO operation on the file descriptor that failed due to the file descriptor not being
ready. Returning a `WouldBlock` error in any other situation will
incorrectly clear the readiness flag, which can cause the file descriptor to
behave incorrectly.

The closure should not perform the IO operation using any of the methods
defined on the Tokio `AsyncFd` type, as this will mess with the
readiness flag and can cause the file descriptor to behave incorrectly.

This method is not intended to be used with combined interests.
The closure should perform only one type of IO operation, so it should not
require more than one ready state. This method may panic or sleep forever
if it is called with a combined interest.

## tokio::try_io (function)

Tries to read or write from the pipe using a user-provided IO operation.

If the pipe is ready, the provided closure is called. The closure
should attempt to perform IO operation from the pipe by manually
calling the appropriate syscall. If the operation fails because the
pipe is not actually ready, then the closure should return a
`WouldBlock` error and the readiness flag is cleared. The return value
of the closure is then returned by `try_io`.

If the pipe is not ready, then the closure is not called
and a `WouldBlock` error is returned.

The closure should only return a `WouldBlock` error if it has performed
an IO operation on the pipe that failed due to the pipe not being
ready. Returning a `WouldBlock` error in any other situation will
incorrectly clear the readiness flag, which can cause the pipe to
behave incorrectly.

The closure should not perform the IO operation using any of the
methods defined on the Tokio `NamedPipeServer` type, as this will mess with
the readiness flag and can cause the pipe to behave incorrectly.

This method is not intended to be used with combined interests.
The closure should perform only one type of IO operation, so it should not
require more than one ready state. This method may panic or sleep forever
if it is called with a combined interest.

Usually, [`readable()`], [`writable()`] or [`ready()`] is used with this function.

[`readable()`]: NamedPipeServer::readable()
[`writable()`]: NamedPipeServer::writable()
[`ready()`]: NamedPipeServer::ready()

## tokio::try_io (function)

Tries to read or write from the pipe using a user-provided IO operation.

If the pipe is ready, the provided closure is called. The closure
should attempt to perform IO operation from the pipe by manually
calling the appropriate syscall. If the operation fails because the
pipe is not actually ready, then the closure should return a
`WouldBlock` error and the readiness flag is cleared. The return value
of the closure is then returned by `try_io`.

If the pipe is not ready, then the closure is not called
and a `WouldBlock` error is returned.

The closure should only return a `WouldBlock` error if it has performed
an IO operation on the pipe that failed due to the pipe not being
ready. Returning a `WouldBlock` error in any other situation will
incorrectly clear the readiness flag, which can cause the pipe to
behave incorrectly.

The closure should not perform the IO operation using any of the methods
defined on the Tokio `NamedPipeClient` type, as this will mess with the
readiness flag and can cause the pipe to behave incorrectly.

This method is not intended to be used with combined interests.
The closure should perform only one type of IO operation, so it should not
require more than one ready state. This method may panic or sleep forever
if it is called with a combined interest.

Usually, [`readable()`], [`writable()`] or [`ready()`] is used with this function.

[`readable()`]: NamedPipeClient::readable()
[`writable()`]: NamedPipeClient::writable()
[`ready()`]: NamedPipeClient::ready()

## tokio::try_io (function)

Tries to read or write from the socket using a user-provided IO operation.

If the socket is ready, the provided closure is called. The closure
should attempt to perform IO operation on the socket by manually
calling the appropriate syscall. If the operation fails because the
socket is not actually ready, then the closure should return a
`WouldBlock` error and the readiness flag is cleared. The return value
of the closure is then returned by `try_io`.

If the socket is not ready, then the closure is not called
and a `WouldBlock` error is returned.

The closure should only return a `WouldBlock` error if it has performed
an IO operation on the socket that failed due to the socket not being
ready. Returning a `WouldBlock` error in any other situation will
incorrectly clear the readiness flag, which can cause the socket to
behave incorrectly.

The closure should not perform the IO operation using any of the methods
defined on the Tokio `TcpStream` type, as this will mess with the
readiness flag and can cause the socket to behave incorrectly.

This method is not intended to be used with combined interests.
The closure should perform only one type of IO operation, so it should not
require more than one ready state. This method may panic or sleep forever
if it is called with a combined interest.

Usually, [`readable()`], [`writable()`] or [`ready()`] is used with this function.

[`readable()`]: TcpStream::readable()
[`writable()`]: TcpStream::writable()
[`ready()`]: TcpStream::ready()

## tokio::try_io (function)

Tries to read or write from the socket using a user-provided IO operation.

If the socket is ready, the provided closure is called. The closure
should attempt to perform IO operation on the socket by manually
calling the appropriate syscall. If the operation fails because the
socket is not actually ready, then the closure should return a
`WouldBlock` error and the readiness flag is cleared. The return value
of the closure is then returned by `try_io`.

If the socket is not ready, then the closure is not called
and a `WouldBlock` error is returned.

The closure should only return a `WouldBlock` error if it has performed
an IO operation on the socket that failed due to the socket not being
ready. Returning a `WouldBlock` error in any other situation will
incorrectly clear the readiness flag, which can cause the socket to
behave incorrectly.

The closure should not perform the IO operation using any of the methods
defined on the Tokio `UdpSocket` type, as this will mess with the
readiness flag and can cause the socket to behave incorrectly.

This method is not intended to be used with combined interests.
The closure should perform only one type of IO operation, so it should not
require more than one ready state. This method may panic or sleep forever
if it is called with a combined interest.

Usually, [`readable()`], [`writable()`] or [`ready()`] is used with this function.

[`readable()`]: UdpSocket::readable()
[`writable()`]: UdpSocket::writable()
[`ready()`]: UdpSocket::ready()

## tokio::try_io (function)

Tries to read or write from the socket using a user-provided IO operation.

If the socket is ready, the provided closure is called. The closure
should attempt to perform IO operation on the socket by manually
calling the appropriate syscall. If the operation fails because the
socket is not actually ready, then the closure should return a
`WouldBlock` error and the readiness flag is cleared. The return value
of the closure is then returned by `try_io`.

If the socket is not ready, then the closure is not called
and a `WouldBlock` error is returned.

The closure should only return a `WouldBlock` error if it has performed
an IO operation on the socket that failed due to the socket not being
ready. Returning a `WouldBlock` error in any other situation will
incorrectly clear the readiness flag, which can cause the socket to
behave incorrectly.

The closure should not perform the IO operation using any of the methods
defined on the Tokio `UnixStream` type, as this will mess with the
readiness flag and can cause the socket to behave incorrectly.

This method is not intended to be used with combined interests.
The closure should perform only one type of IO operation, so it should not
require more than one ready state. This method may panic or sleep forever
if it is called with a combined interest.

Usually, [`readable()`], [`writable()`] or [`ready()`] is used with this function.

[`readable()`]: UnixStream::readable()
[`writable()`]: UnixStream::writable()
[`ready()`]: UnixStream::ready()

## tokio::try_io (function)

Tries to read to the socket using a user-provided IO operation.

If the socket is ready, the provided closure is called. The closure
should attempt to perform IO operation on the socket by manually
calling the appropriate syscall. If the operation fails because the
socket is not actually ready, then the closure should return a
`WouldBlock` error and the readiness flag is cleared. The return value
of the closure is then returned by `try_io`.

If the socket is not ready, then the closure is not called
and a `WouldBlock` error is returned.

The closure should only return a `WouldBlock` error if it has performed
an IO operation on the socket that failed due to the socket not being
ready. Returning a `WouldBlock` error in any other situation will
incorrectly clear the readiness flag, which can cause the socket to
behave incorrectly.

The closure should not perform the IO operation using any of the methods
defined on the Tokio `pipe::Receiver` type, as this will mess with the
readiness flag and can cause the socket to behave incorrectly.

Usually, [`readable()`] or [`ready()`] is used with this function.

[`readable()`]: Self::readable()
[`ready()`]: Self::ready()

## tokio::try_io (function)

Tries to write from the socket using a user-provided IO operation.

If the socket is ready, the provided closure is called. The closure
should attempt to perform IO operation on the socket by manually
calling the appropriate syscall. If the operation fails because the
socket is not actually ready, then the closure should return a
`WouldBlock` error and the readiness flag is cleared. The return value
of the closure is then returned by `try_io`.

If the socket is not ready, then the closure is not called
and a `WouldBlock` error is returned.

The closure should only return a `WouldBlock` error if it has performed
an IO operation on the socket that failed due to the socket not being
ready. Returning a `WouldBlock` error in any other situation will
incorrectly clear the readiness flag, which can cause the socket to
behave incorrectly.

The closure should not perform the IO operation using any of the methods
defined on the Tokio `pipe::Sender` type, as this will mess with the
readiness flag and can cause the socket to behave incorrectly.

Usually, [`writable()`] or [`ready()`] is used with this function.

[`writable()`]: Self::writable()
[`ready()`]: Self::ready()

## tokio::try_io_mut (function)

Tries to read or write from the file descriptor using a user-provided IO operation.

The behavior is the same as [`try_io`], except that the closure can mutate the inner
value of the [`AsyncFd`].

[`try_io`]: AsyncFd::try_io

## tokio::try_join (macro)

Waits on multiple concurrent branches, returning when **all** branches
complete with `Ok(_)` or on the first `Err(_)`.

The `try_join!` macro must be used inside of async functions, closures, and
blocks.

Similar to [`join!`], the `try_join!` macro takes a list of async
expressions and evaluates them concurrently on the same task. Each async
expression evaluates to a future and the futures from each expression are
multiplexed on the current task. The `try_join!` macro returns when **all**
branches return with `Ok` or when the **first** branch returns with `Err`.

[`join!`]: macro@join

### tokio::try_join (macro) › Notes

The supplied futures are stored inline and do not require allocating a
`Vec`.

### tokio::try_join (macro) › Runtime characteristics

By running all async expressions on the current task, the expressions are
able to run **concurrently** but not in **parallel**. This means all
expressions are run on the same thread and if one branch blocks the thread,
all other expressions will be unable to continue. If parallelism is
required, spawn each async expression using [`tokio::spawn`] and pass the
join handle to `try_join!`.

[`tokio::spawn`]: crate::spawn

### tokio::try_join (macro) › Fairness

By default, `try_join!`'s generated future rotates which
contained future is polled first whenever it is woken.

This behavior can be overridden by adding `biased;` to the beginning of the
macro usage. See the examples for details. This will cause `try_join` to poll
the futures in the order they appear from top to bottom.

You may want this if your futures may interact in a way where known polling order is significant.

But there is an important caveat to this mode. It becomes your responsibility
to ensure that the polling order of your futures is fair. If for example you
are joining a stream and a shutdown future, and the stream has a
huge volume of messages that takes a long time to finish processing per poll, you should
place the shutdown future earlier in the `try_join!` list to ensure that it is
always polled, and will not be delayed due to the stream future taking a long time to return
`Poll::Pending`.

### tokio::try_join (macro) › Examples

Basic `try_join` with two branches.

```
async fn do_stuff_async() -> Result<(), &'static str> {
    // async work
# Ok(())
}

async fn more_async_work() -> Result<(), &'static str> {
    // more here
# Ok(())
}

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let res = tokio::try_join!(
    do_stuff_async(),
    more_async_work());

match res {
    Ok((first, second)) => {
        // do something with the values
    }
    Err(err) => {
        println!("processing failed; error = {}", err);
    }
}
# }
```

Using `try_join!` with spawned tasks.

```
use tokio::task::JoinHandle;

async fn do_stuff_async() -> Result<(), &'static str> {
    // async work
# Err("failed")
}

async fn more_async_work() -> Result<(), &'static str> {
    // more here
# Ok(())
}

async fn flatten<T>(handle: JoinHandle<Result<T, &'static str>>) -> Result<T, &'static str> {
    match handle.await {
        Ok(Ok(result)) => Ok(result),
        Ok(Err(err)) => Err(err),
        Err(err) => Err("handling failed"),
    }
}

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let handle1 = tokio::spawn(do_stuff_async());
let handle2 = tokio::spawn(more_async_work());
match tokio::try_join!(flatten(handle1), flatten(handle2)) {
    Ok(val) => {
        // do something with the values
    }
    Err(err) => {
        println!("Failed with {}.", err);
        # assert_eq!(err, "failed");
    }
}
# }
```
Using the `biased;` mode to control polling order.

```
async fn do_stuff_async() -> Result<(), &'static str> {
    // async work
# Ok(())
}

async fn more_async_work() -> Result<(), &'static str> {
    // more here
# Ok(())
}

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let res = tokio::try_join!(
    biased;
    do_stuff_async(),
    more_async_work()
);

match res {
    Ok((first, second)) => {
        // do something with the values
    }
    Err(err) => {
        println!("processing failed; error = {}", err);
    }
}
# }
```

## tokio::try_join_next (function)

Tries to join one of the tasks in the set that has completed and return its output.

Returns `None` if there are no completed tasks, or if the set is empty.

## tokio::try_join_next_with_id (function)

Tries to join one of the tasks in the set that has completed and return its output,
along with the [task ID] of the completed task.

Returns `None` if there are no completed tasks, or if the set is empty.

When this method returns an error, then the id of the task that failed can be accessed
using the [`JoinError::id`] method.

[task ID]: crate::task::Id
[`JoinError::id`]: fn@crate::task::JoinError::id

## tokio::try_lock (function)

Attempts to acquire the lock, and returns [`TryLockError`] if the
lock is currently held somewhere else.

[`TryLockError`]: TryLockError
### tokio::try_lock (function) › Examples

```
use tokio::sync::Mutex;
# async fn dox() -> Result<(), tokio::sync::TryLockError> {

let mutex = Mutex::new(1);

let n = mutex.try_lock()?;
assert_eq!(*n, 1);
# Ok(())
# }
```

## tokio::try_lock_owned (function)

Attempts to acquire the lock, and returns [`TryLockError`] if the lock
is currently held somewhere else.

This method is identical to [`Mutex::try_lock`], except that the
returned  guard references the `Mutex` with an [`Arc`] rather than by
borrowing it. Therefore, the `Mutex` must be wrapped in an `Arc` to call
this method, and the guard will live for the `'static` lifetime, as it
keeps the `Mutex` alive by holding an `Arc`.

[`TryLockError`]: TryLockError
[`Arc`]: std::sync::Arc
### tokio::try_lock_owned (function) › Examples

```
use tokio::sync::Mutex;
use std::sync::Arc;
# async fn dox() -> Result<(), tokio::sync::TryLockError> {

let mutex = Arc::new(Mutex::new(1));

let n = mutex.clone().try_lock_owned()?;
assert_eq!(*n, 1);
# Ok(())
# }
```

## tokio::try_map (function)

Attempts to make a new [`MappedMutexGuard`] for a component of the locked data. The
original guard is returned if the closure returns `None`.

This operation cannot fail as the [`MappedMutexGuard`] passed in already locked the mutex.

This is an associated function that needs to be used as `MappedMutexGuard::try_map(...)`. A
method would interfere with methods of the same name on the contents of the locked data.

[`MappedMutexGuard`]: struct@MappedMutexGuard

## tokio::try_map (function)

Attempts to make a new [`MappedMutexGuard`] for a component of the locked data. The
original guard is returned if the closure returns `None`.

This operation cannot fail as the [`MutexGuard`] passed in already locked the mutex.

This is an associated function that needs to be used as `MutexGuard::try_map(...)`. A
method would interfere with methods of the same name on the contents of the locked data.

### tokio::try_map (function) › Examples

```
use tokio::sync::{Mutex, MutexGuard};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Foo(u32);

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let foo = Mutex::new(Foo(1));

{
    let mut mapped = MutexGuard::try_map(foo.lock().await, |f| Some(&mut f.0))
        .expect("should not fail");
    *mapped = 2;
}

assert_eq!(Foo(2), *foo.lock().await);
# }
```

[`MutexGuard`]: struct@MutexGuard
[`MappedMutexGuard`]: struct@MappedMutexGuard

## tokio::try_map (function)

Attempts to make a new [`OwnedMappedMutexGuard`] for a component of the locked data. The
original guard is returned if the closure returns `None`.

This operation cannot fail as the [`OwnedMutexGuard`] passed in already locked the mutex.

This is an associated function that needs to be used as `OwnedMutexGuard::try_map(...)`. A
method would interfere with methods of the same name on the contents of the locked data.

### tokio::try_map (function) › Examples

```
use tokio::sync::{Mutex, OwnedMutexGuard};
use std::sync::Arc;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Foo(u32);

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let foo = Arc::new(Mutex::new(Foo(1)));

{
    let mut mapped = OwnedMutexGuard::try_map(foo.clone().lock_owned().await, |f| Some(&mut f.0))
        .expect("should not fail");
    *mapped = 2;
}

assert_eq!(Foo(2), *foo.lock().await);
# }
```

[`OwnedMutexGuard`]: struct@OwnedMutexGuard
[`OwnedMappedMutexGuard`]: struct@OwnedMappedMutexGuard

## tokio::try_map (function)

Attempts to make a new [`OwnedMappedMutexGuard`] for a component of the locked data. The
original guard is returned if the closure returns `None`.

This operation cannot fail as the [`OwnedMutexGuard`] passed in already locked the mutex.

This is an associated function that needs to be used as `OwnedMutexGuard::try_map(...)`. A
method would interfere with methods of the same name on the contents of the locked data.

[`OwnedMutexGuard`]: struct@OwnedMutexGuard
[`OwnedMappedMutexGuard`]: struct@OwnedMappedMutexGuard

## tokio::try_map (function)

Attempts to make a new [`OwnedRwLockMappedWriteGuard`] for a component
of the locked data. The original guard is returned if the closure
returns `None`.

This operation cannot fail as the `OwnedRwLockWriteGuard` passed in
already locked the data.

This is an associated function that needs to be
used as `OwnedRwLockWriteGuard::try_map(...)`. A method would interfere
with methods of the same name on the contents of the locked data.

[`RwLockMappedWriteGuard`]: struct@crate::sync::RwLockMappedWriteGuard

### tokio::try_map (function) › Examples

```
use std::sync::Arc;
use tokio::sync::{RwLock, OwnedRwLockWriteGuard};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Foo(u32);

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let lock = Arc::new(RwLock::new(Foo(1)));

{
    let guard = Arc::clone(&lock).write_owned().await;
    let mut guard = OwnedRwLockWriteGuard::try_map(guard, |f| Some(&mut f.0)).expect("should not fail");
    *guard = 2;
}

assert_eq!(Foo(2), *lock.read().await);
# }
```

## tokio::try_map (function)

Attempts to make a new [`OwnedRwLockReadGuard`] for a component of the
locked data. The original guard is returned if the closure returns
`None`.

This operation cannot fail as the `OwnedRwLockReadGuard` passed in
already locked the data.

This is an associated function that needs to be used as
`OwnedRwLockReadGuard::try_map(..)`. A method would interfere with
methods of the same name on the contents of the locked data.

### tokio::try_map (function) › Examples

```
use std::sync::Arc;
use tokio::sync::{RwLock, OwnedRwLockReadGuard};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Foo(u32);

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let lock = Arc::new(RwLock::new(Foo(1)));

let guard = lock.read_owned().await;
let guard = OwnedRwLockReadGuard::try_map(guard, |f| Some(&f.0)).expect("should not fail");

assert_eq!(1, *guard);
# }
```

## tokio::try_map (function)

Attempts to make a new [`RwLockMappedWriteGuard`] for a component of
the locked data. The original guard is returned if the closure returns
`None`.

This operation cannot fail as the `RwLockMappedWriteGuard` passed in already
locked the data.

This is an associated function that needs to be
used as `RwLockMappedWriteGuard::try_map(...)`. A method would interfere
with methods of the same name on the contents of the locked data.

This is an asynchronous version of [`RwLockWriteGuard::try_map`] from
the [`parking_lot` crate].

[`RwLockWriteGuard::try_map`]: https://docs.rs/lock_api/latest/lock_api/struct.RwLockWriteGuard.html#method.try_map
[`parking_lot` crate]: https://crates.io/crates/parking_lot

### tokio::try_map (function) › Examples

```
use tokio::sync::{RwLock, RwLockWriteGuard};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Foo(u32);

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let lock = RwLock::new(Foo(1));

{
    let guard = lock.write().await;
    let mut guard = RwLockWriteGuard::try_map(guard, |f| Some(&mut f.0)).expect("should not fail");
    *guard = 2;
}

assert_eq!(Foo(2), *lock.read().await);
# }
```

## tokio::try_map (function)

Attempts to make a new [`RwLockMappedWriteGuard`] for a component of
the locked data. The original guard is returned if the closure returns
`None`.

This operation cannot fail as the `RwLockWriteGuard` passed in already
locked the data.

This is an associated function that needs to be
used as `RwLockWriteGuard::try_map(...)`. A method would interfere with
methods of the same name on the contents of the locked data.

This is an asynchronous version of [`RwLockWriteGuard::try_map`] from
the [`parking_lot` crate].

[`RwLockMappedWriteGuard`]: struct@crate::sync::RwLockMappedWriteGuard
[`RwLockWriteGuard::try_map`]: https://docs.rs/lock_api/latest/lock_api/struct.RwLockWriteGuard.html#method.try_map
[`parking_lot` crate]: https://crates.io/crates/parking_lot

### tokio::try_map (function) › Examples

```
use tokio::sync::{RwLock, RwLockWriteGuard};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Foo(u32);

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let lock = RwLock::new(Foo(1));

{
    let guard = lock.write().await;
    let mut guard = RwLockWriteGuard::try_map(guard, |f| Some(&mut f.0)).expect("should not fail");
    *guard = 2;
}

assert_eq!(Foo(2), *lock.read().await);
# }
```

## tokio::try_map (function)

Attempts to make a new [`RwLockReadGuard`] for a component of the
locked data. The original guard is returned if the closure returns
`None`.

This operation cannot fail as the `RwLockReadGuard` passed in already
locked the data.

This is an associated function that needs to be used as
`RwLockReadGuard::try_map(..)`. A method would interfere with methods of the
same name on the contents of the locked data.

This is an asynchronous version of [`RwLockReadGuard::try_map`] from the
[`parking_lot` crate].

[`RwLockReadGuard::try_map`]: https://docs.rs/lock_api/latest/lock_api/struct.RwLockReadGuard.html#method.try_map
[`parking_lot` crate]: https://crates.io/crates/parking_lot

### tokio::try_map (function) › Examples

```
use tokio::sync::{RwLock, RwLockReadGuard};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Foo(u32);

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let lock = RwLock::new(Foo(1));

let guard = lock.read().await;
let guard = RwLockReadGuard::try_map(guard, |f| Some(&f.0)).expect("should not fail");

assert_eq!(1, *guard);
# }
```

## tokio::try_map (function)

Attempts to make a new `OwnedRwLockMappedWriteGuard` for a component
of the locked data. The original guard is returned if the closure
returns `None`.

This operation cannot fail as the `OwnedRwLockMappedWriteGuard` passed
in already locked the data.

This is an associated function that needs to be
used as `OwnedRwLockMappedWriteGuard::try_map(...)`. A method would interfere with
methods of the same name on the contents of the locked data.

### tokio::try_map (function) › Examples

```
use std::sync::Arc;
use tokio::sync::{RwLock, OwnedRwLockWriteGuard};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Foo(u32);

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let lock = Arc::new(RwLock::new(Foo(1)));

{
    let guard = Arc::clone(&lock).write_owned().await;
    let mut guard = OwnedRwLockWriteGuard::try_map(guard, |f| Some(&mut f.0)).expect("should not fail");
    *guard = 2;
}

assert_eq!(Foo(2), *lock.read().await);
# }
```

## tokio::try_new (function)

Creates an [`AsyncFd`] backed by (and taking ownership of) an object
implementing [`AsRawFd`]. The backing file descriptor is cached at the
time of creation.

Only configures the [`Interest::READABLE`] and [`Interest::WRITABLE`] interests. For more
control, use [`AsyncFd::try_with_interest`].

This method must be called in the context of a tokio runtime.

In the case of failure, it returns [`AsyncFdTryNewError`] that contains the original object
passed to this function.

### tokio::try_new (function) › Panics

This function panics if there is no current reactor set, or if the `rt`
feature flag is not enabled.

## tokio::try_peek (function)

Tries to receive data on the connected address without removing it from the input queue.
On success, returns the number of bytes read.

When there is no pending data, `Err(io::ErrorKind::WouldBlock)` is
returned. This function is usually paired with `readable()`.

### tokio::try_peek (function) › Notes

On Windows, if the data is larger than the buffer specified, the buffer
is filled with the first part of the data, and peek returns the error
`WSAEMSGSIZE(10040)`. The excess data is lost.
Make sure to always use a sufficiently large buffer to hold the
maximum UDP packet size, which can be up to 65536 bytes in size.

MacOS will return an error if you pass a zero-sized buffer.

If you're merely interested in learning the sender of the data at the head of the queue,
try [`try_peek_sender`].

Note that the socket address **cannot** be implicitly trusted, because it is relatively
trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
Because UDP is stateless and does not validate the origin of a packet,
the attacker does not need to be able to intercept traffic in order to interfere.
It is important to be aware of this when designing your application-level protocol.

[`try_peek_sender`]: method@Self::try_peek_sender
[packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection

## tokio::try_peek_from (function)

Tries to receive data on the socket without removing it from the input queue.
On success, returns the number of bytes read and the sending address of the
datagram.

When there is no pending data, `Err(io::ErrorKind::WouldBlock)` is
returned. This function is usually paired with `readable()`.

### tokio::try_peek_from (function) › Notes

On Windows, if the data is larger than the buffer specified, the buffer
is filled with the first part of the data, and peek returns the error
`WSAEMSGSIZE(10040)`. The excess data is lost.
Make sure to always use a sufficiently large buffer to hold the
maximum UDP packet size, which can be up to 65536 bytes in size.

MacOS will return an error if you pass a zero-sized buffer.

If you're merely interested in learning the sender of the data at the head of the queue,
try [`try_peek_sender`].

Note that the socket address **cannot** be implicitly trusted, because it is relatively
trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
Because UDP is stateless and does not validate the origin of a packet,
the attacker does not need to be able to intercept traffic in order to interfere.
It is important to be aware of this when designing your application-level protocol.

[`try_peek_sender`]: method@Self::try_peek_sender
[packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection

## tokio::try_peek_sender (function)

Try to retrieve the sender of the data at the head of the input queue.

When there is no pending data, `Err(io::ErrorKind::WouldBlock)` is
returned. This function is usually paired with `readable()`.

Note that the socket address **cannot** be implicitly trusted, because it is relatively
trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
Because UDP is stateless and does not validate the origin of a packet,
the attacker does not need to be able to intercept traffic in order to interfere.
It is important to be aware of this when designing your application-level protocol.

[packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection

## tokio::try_read (function)

Attempts to acquire this `RwLock` with shared read access.

If the access couldn't be acquired immediately, returns [`TryLockError`].
Otherwise, an RAII guard is returned which will release read access
when dropped.

[`TryLockError`]: TryLockError

### tokio::try_read (function) › Examples

```
use std::sync::Arc;
use tokio::sync::RwLock;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let lock = Arc::new(RwLock::new(1));
let c_lock = lock.clone();

let v = lock.try_read().unwrap();
assert_eq!(*v, 1);

tokio::spawn(async move {
    // While main has an active read lock, we acquire one too.
    let n = c_lock.read().await;
    assert_eq!(*n, 1);
}).await.expect("The spawned task has panicked");

// Drop the guard when spawned task finishes.
drop(v);
# }
```

## tokio::try_read (function)

Tries to read data from the pipe into the provided buffer, returning how
many bytes were read.

Reads any pending data from the pipe but does not wait for new data
to arrive. On success, returns the number of bytes read. Because
`try_read()` is non-blocking, the buffer does not have to be stored by
the async task and can exist entirely on the stack.

Usually [`readable()`] is used with this function.

[`readable()`]: Self::readable()

### tokio::try_read (function) › Return

If data is successfully read, `Ok(n)` is returned, where `n` is the
number of bytes read. If `n` is `0`, then it can indicate one of two scenarios:

1. The pipe's writing end is closed and will no longer write data.
2. The specified buffer was 0 bytes in length.

If the pipe is not ready to read data,
`Err(io::ErrorKind::WouldBlock)` is returned.

### tokio::try_read (function) › Notes

To avoid unnecessary syscalls, this will only attempt the read
operation if the OS has informed Tokio that this pipe has become
readable. Because of this, `try_read()` may fail with a
[`WouldBlock`] error if Tokio has not yet heard from the OS that
this pipe has become readable.

### tokio::try_read (function) › Examples

```no_run
use tokio::net::unix::pipe;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    // Open a reading end of a fifo
    let rx = pipe::OpenOptions::new().open_receiver("path/to/a/fifo")?;

    let mut msg = vec![0; 1024];

    loop {
        // Wait for the pipe to be readable
        rx.readable().await?;

        // Try to read data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match rx.try_read(&mut msg) {
            Ok(n) => {
                msg.truncate(n);
                break;
            }
            Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    println!("GOT = {:?}", msg);
    Ok(())
}
```

[`WouldBlock`]: std::io::ErrorKind::WouldBlock

## tokio::try_read (function)

Tries to read data from the pipe into the provided buffer, returning how
many bytes were read.

Receives any pending data from the pipe but does not wait for new data
to arrive. On success, returns the number of bytes read. Because
`try_read()` is non-blocking, the buffer does not have to be stored by
the async task and can exist entirely on the stack.

Usually, [`readable()`] or [`ready()`] is used with this function.

[`readable()`]: NamedPipeClient::readable()
[`ready()`]: NamedPipeClient::ready()

### tokio::try_read (function) › Return

If data is successfully read, `Ok(n)` is returned, where `n` is the
number of bytes read. If `n` is `0`, then it can indicate one of two scenarios:

1. The pipe's read half is closed and will no longer yield data.
2. The specified buffer was 0 bytes in length.

If the pipe is not ready to read data,
`Err(io::ErrorKind::WouldBlock)` is returned.

### tokio::try_read (function) › Examples

```no_run
use tokio::net::windows::named_pipe;
use std::error::Error;
use std::io;

const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-client-try-read";

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let client = named_pipe::ClientOptions::new().open(PIPE_NAME)?;

    loop {
        // Wait for the pipe to be readable
        client.readable().await?;

        // Creating the buffer **after** the `await` prevents it from
        // being stored in the async task.
        let mut buf = [0; 4096];

        // Try to read data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match client.try_read(&mut buf) {
            Ok(0) => break,
            Ok(n) => {
                println!("read {} bytes", n);
            }
            Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    Ok(())
}
```

## tokio::try_read (function)

Tries to read data from the pipe into the provided buffer, returning how
many bytes were read.

Receives any pending data from the pipe but does not wait for new data
to arrive. On success, returns the number of bytes read. Because
`try_read()` is non-blocking, the buffer does not have to be stored by
the async task and can exist entirely on the stack.

Usually, [`readable()`] or [`ready()`] is used with this function.

[`readable()`]: NamedPipeServer::readable()
[`ready()`]: NamedPipeServer::ready()

### tokio::try_read (function) › Return

If data is successfully read, `Ok(n)` is returned, where `n` is the
number of bytes read. If `n` is `0`, then it can indicate one of two scenarios:

1. The pipe's read half is closed and will no longer yield data.
2. The specified buffer was 0 bytes in length.

If the pipe is not ready to read data,
`Err(io::ErrorKind::WouldBlock)` is returned.

### tokio::try_read (function) › Examples

```no_run
use tokio::net::windows::named_pipe;
use std::error::Error;
use std::io;

const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-server-try-read";

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let server = named_pipe::ServerOptions::new()
        .create(PIPE_NAME)?;

    loop {
        // Wait for the pipe to be readable
        server.readable().await?;

        // Creating the buffer **after** the `await` prevents it from
        // being stored in the async task.
        let mut buf = [0; 4096];

        // Try to read data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match server.try_read(&mut buf) {
            Ok(0) => break,
            Ok(n) => {
                println!("read {} bytes", n);
            }
            Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    Ok(())
}
```

## tokio::try_read (function)

Tries to read data from the stream into the provided buffer, returning how
many bytes were read.

Receives any pending data from the socket but does not wait for new data
to arrive. On success, returns the number of bytes read. Because
`try_read()` is non-blocking, the buffer does not have to be stored by
the async task and can exist entirely on the stack.

Usually, [`readable()`] or [`ready()`] is used with this function.

[`readable()`]: Self::readable()
[`ready()`]: Self::ready()

### tokio::try_read (function) › Return

If data is successfully read, `Ok(n)` is returned, where `n` is the
number of bytes read. If `n` is `0`, then it can indicate one of two scenarios:

1. The stream's read half is closed and will no longer yield data.
2. The specified buffer was 0 bytes in length.

If the stream is not ready to read data,
`Err(io::ErrorKind::WouldBlock)` is returned.

## tokio::try_read (function)

Tries to read data from the stream into the provided buffer, returning how
many bytes were read.

Receives any pending data from the socket but does not wait for new data
to arrive. On success, returns the number of bytes read. Because
`try_read()` is non-blocking, the buffer does not have to be stored by
the async task and can exist entirely on the stack.

Usually, [`readable()`] or [`ready()`] is used with this function.

[`readable()`]: Self::readable()
[`ready()`]: Self::ready()

### tokio::try_read (function) › Return

If data is successfully read, `Ok(n)` is returned, where `n` is the
number of bytes read. If `n` is `0`, then it can indicate one of two scenarios:

1. The stream's read half is closed and will no longer yield data.
2. The specified buffer was 0 bytes in length.

If the stream is not ready to read data,
`Err(io::ErrorKind::WouldBlock)` is returned.

## tokio::try_read (function)

Tries to read data from the stream into the provided buffer, returning how
many bytes were read.

Receives any pending data from the socket but does not wait for new data
to arrive. On success, returns the number of bytes read. Because
`try_read()` is non-blocking, the buffer does not have to be stored by
the async task and can exist entirely on the stack.

Usually, [`readable()`] or [`ready()`] is used with this function.

[`readable()`]: Self::readable()
[`ready()`]: Self::ready()

### tokio::try_read (function) › Return

If data is successfully read, `Ok(n)` is returned, where `n` is the
number of bytes read. If `n` is `0`, then it can indicate one of two scenarios:

1. The stream's read half is closed and will no longer yield data.
2. The specified buffer was 0 bytes in length.

If the stream is not ready to read data,
`Err(io::ErrorKind::WouldBlock)` is returned.

## tokio::try_read (function)

Tries to read data from the stream into the provided buffer, returning how
many bytes were read.

Receives any pending data from the socket but does not wait for new data
to arrive. On success, returns the number of bytes read. Because
`try_read()` is non-blocking, the buffer does not have to be stored by
the async task and can exist entirely on the stack.

Usually, [`readable()`] or [`ready()`] is used with this function.

[`readable()`]: Self::readable()
[`ready()`]: Self::ready()

### tokio::try_read (function) › Return

If data is successfully read, `Ok(n)` is returned, where `n` is the
number of bytes read. If `n` is `0`, then it can indicate one of two scenarios:

1. The stream's read half is closed and will no longer yield data.
2. The specified buffer was 0 bytes in length.

If the stream is not ready to read data,
`Err(io::ErrorKind::WouldBlock)` is returned.

## tokio::try_read (function)

Tries to read data from the stream into the provided buffer, returning how
many bytes were read.

Receives any pending data from the socket but does not wait for new data
to arrive. On success, returns the number of bytes read. Because
`try_read()` is non-blocking, the buffer does not have to be stored by
the async task and can exist entirely on the stack.

Usually, [`readable()`] or [`ready()`] is used with this function.

[`readable()`]: TcpStream::readable()
[`ready()`]: TcpStream::ready()

### tokio::try_read (function) › Return

If data is successfully read, `Ok(n)` is returned, where `n` is the
number of bytes read. If `n` is `0`, then it can indicate one of two scenarios:

1. The stream's read half is closed and will no longer yield data.
2. The specified buffer was 0 bytes in length.

If the stream is not ready to read data,
`Err(io::ErrorKind::WouldBlock)` is returned.

### tokio::try_read (function) › Examples

```no_run
use tokio::net::TcpStream;
use std::error::Error;
use std::io;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // Connect to a peer
    let stream = TcpStream::connect("127.0.0.1:8080").await?;

    loop {
        // Wait for the socket to be readable
        stream.readable().await?;

        // Creating the buffer **after** the `await` prevents it from
        // being stored in the async task.
        let mut buf = [0; 4096];

        // Try to read data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match stream.try_read(&mut buf) {
            Ok(0) => break,
            Ok(n) => {
                println!("read {} bytes", n);
            }
            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    Ok(())
}
```

## tokio::try_read (function)

Try to read data from the stream into the provided buffer, returning how
many bytes were read.

Receives any pending data from the socket but does not wait for new data
to arrive. On success, returns the number of bytes read. Because
`try_read()` is non-blocking, the buffer does not have to be stored by
the async task and can exist entirely on the stack.

Usually, [`readable()`] or [`ready()`] is used with this function.

[`readable()`]: UnixStream::readable()
[`ready()`]: UnixStream::ready()

### tokio::try_read (function) › Return

If data is successfully read, `Ok(n)` is returned, where `n` is the
number of bytes read. If `n` is `0`, then it can indicate one of two scenarios:

1. The stream's read half is closed and will no longer yield data.
2. The specified buffer was 0 bytes in length.

If the stream is not ready to read data,
`Err(io::ErrorKind::WouldBlock)` is returned.

### tokio::try_read (function) › Examples

```no_run
use tokio::net::UnixStream;
use std::error::Error;
use std::io;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // Connect to a peer
    let dir = tempfile::tempdir().unwrap();
    let bind_path = dir.path().join("bind_path");
    let stream = UnixStream::connect(bind_path).await?;

    loop {
        // Wait for the socket to be readable
        stream.readable().await?;

        // Creating the buffer **after** the `await` prevents it from
        // being stored in the async task.
        let mut buf = [0; 4096];

        // Try to read data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match stream.try_read(&mut buf) {
            Ok(0) => break,
            Ok(n) => {
                println!("read {} bytes", n);
            }
            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    Ok(())
}
```

## tokio::try_read_buf (function)

Tries to read data from the pipe into the provided buffer, advancing the
buffer's internal cursor, returning how many bytes were read.

Reads any pending data from the pipe but does not wait for new data
to arrive. On success, returns the number of bytes read. Because
`try_read_buf()` is non-blocking, the buffer does not have to be stored by
the async task and can exist entirely on the stack.

Usually, [`readable()`] or [`ready()`] is used with this function.

[`readable()`]: Self::readable
[`ready()`]: Self::ready

### tokio::try_read_buf (function) › Return

If data is successfully read, `Ok(n)` is returned, where `n` is the
number of bytes read. `Ok(0)` indicates the pipe's writing end is
closed and will no longer write data. If the pipe is not ready to read
data `Err(io::ErrorKind::WouldBlock)` is returned.

### tokio::try_read_buf (function) › Notes

To avoid unnecessary syscalls, this will only attempt the read
operation if the OS has informed Tokio that this pipe has become
readable. Because of this, `try_read_buf()` may fail with a
[`WouldBlock`] error if Tokio has not yet heard from the OS that
this pipe has become readable.

### tokio::try_read_buf (function) › Examples

```no_run
use tokio::net::unix::pipe;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    // Open a reading end of a fifo
    let rx = pipe::OpenOptions::new().open_receiver("path/to/a/fifo")?;

    loop {
        // Wait for the pipe to be readable
        rx.readable().await?;

        let mut buf = Vec::with_capacity(4096);

        // Try to read data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match rx.try_read_buf(&mut buf) {
            Ok(0) => break,
            Ok(n) => {
                println!("read {} bytes", n);
            }
            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    Ok(())
}
```

[`WouldBlock`]: std::io::ErrorKind::WouldBlock

## tokio::try_read_buf (function)

Tries to read data from the stream into the provided buffer, advancing the
buffer's internal cursor, returning how many bytes were read.

Receives any pending data from the pipe but does not wait for new data
to arrive. On success, returns the number of bytes read. Because
`try_read_buf()` is non-blocking, the buffer does not have to be stored by
the async task and can exist entirely on the stack.

Usually, [`readable()`] or [`ready()`] is used with this function.

[`readable()`]: NamedPipeClient::readable()
[`ready()`]: NamedPipeClient::ready()

### tokio::try_read_buf (function) › Return

If data is successfully read, `Ok(n)` is returned, where `n` is the
number of bytes read. `Ok(0)` indicates the stream's read half is closed
and will no longer yield data. If the stream is not ready to read data
`Err(io::ErrorKind::WouldBlock)` is returned.

### tokio::try_read_buf (function) › Examples

```no_run
use tokio::net::windows::named_pipe;
use std::error::Error;
use std::io;

const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-client-readable";

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let client = named_pipe::ClientOptions::new().open(PIPE_NAME)?;

    loop {
        // Wait for the pipe to be readable
        client.readable().await?;

        let mut buf = Vec::with_capacity(4096);

        // Try to read data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match client.try_read_buf(&mut buf) {
            Ok(0) => break,
            Ok(n) => {
                println!("read {} bytes", n);
            }
            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    Ok(())
}
```

## tokio::try_read_buf (function)

Tries to read data from the stream into the provided buffer, advancing the
buffer's internal cursor, returning how many bytes were read.

Receives any pending data from the pipe but does not wait for new data
to arrive. On success, returns the number of bytes read. Because
`try_read_buf()` is non-blocking, the buffer does not have to be stored by
the async task and can exist entirely on the stack.

Usually, [`readable()`] or [`ready()`] is used with this function.

[`readable()`]: NamedPipeServer::readable()
[`ready()`]: NamedPipeServer::ready()

### tokio::try_read_buf (function) › Return

If data is successfully read, `Ok(n)` is returned, where `n` is the
number of bytes read. `Ok(0)` indicates the stream's read half is closed
and will no longer yield data. If the stream is not ready to read data
`Err(io::ErrorKind::WouldBlock)` is returned.

### tokio::try_read_buf (function) › Examples

```no_run
use tokio::net::windows::named_pipe;
use std::error::Error;
use std::io;

const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-client-readable";

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let server = named_pipe::ServerOptions::new().create(PIPE_NAME)?;

    loop {
        // Wait for the pipe to be readable
        server.readable().await?;

        let mut buf = Vec::with_capacity(4096);

        // Try to read data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match server.try_read_buf(&mut buf) {
            Ok(0) => break,
            Ok(n) => {
                println!("read {} bytes", n);
            }
            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    Ok(())
}
```

## tokio::try_read_buf (function)

Tries to read data from the stream into the provided buffer, advancing the
buffer's internal cursor, returning how many bytes were read.

Receives any pending data from the socket but does not wait for new data
to arrive. On success, returns the number of bytes read. Because
`try_read_buf()` is non-blocking, the buffer does not have to be stored by
the async task and can exist entirely on the stack.

Usually, [`readable()`] or [`ready()`] is used with this function.

[`readable()`]: Self::readable()
[`ready()`]: Self::ready()

### tokio::try_read_buf (function) › Return

If data is successfully read, `Ok(n)` is returned, where `n` is the
number of bytes read. `Ok(0)` indicates the stream's read half is closed
and will no longer yield data. If the stream is not ready to read data

## tokio::try_read_buf (function)

Tries to read data from the stream into the provided buffer, advancing the
buffer's internal cursor, returning how many bytes were read.

Receives any pending data from the socket but does not wait for new data
to arrive. On success, returns the number of bytes read. Because
`try_read_buf()` is non-blocking, the buffer does not have to be stored by
the async task and can exist entirely on the stack.

Usually, [`readable()`] or [`ready()`] is used with this function.

[`readable()`]: Self::readable()
[`ready()`]: Self::ready()

### tokio::try_read_buf (function) › Return

If data is successfully read, `Ok(n)` is returned, where `n` is the
number of bytes read. `Ok(0)` indicates the stream's read half is closed
and will no longer yield data. If the stream is not ready to read data
`Err(io::ErrorKind::WouldBlock)` is returned.

## tokio::try_read_buf (function)

Tries to read data from the stream into the provided buffer, advancing the
buffer's internal cursor, returning how many bytes were read.

Receives any pending data from the socket but does not wait for new data
to arrive. On success, returns the number of bytes read. Because
`try_read_buf()` is non-blocking, the buffer does not have to be stored by
the async task and can exist entirely on the stack.

Usually, [`readable()`] or [`ready()`] is used with this function.

[`readable()`]: Self::readable()
[`ready()`]: Self::ready()

### tokio::try_read_buf (function) › Return

If data is successfully read, `Ok(n)` is returned, where `n` is the
number of bytes read. `Ok(0)` indicates the stream's read half is closed
and will no longer yield data. If the stream is not ready to read data
`Err(io::ErrorKind::WouldBlock)` is returned.

## tokio::try_read_buf (function)

Tries to read data from the stream into the provided buffer, advancing the
buffer's internal cursor, returning how many bytes were read.

Receives any pending data from the socket but does not wait for new data
to arrive. On success, returns the number of bytes read. Because
`try_read_buf()` is non-blocking, the buffer does not have to be stored by
the async task and can exist entirely on the stack.

Usually, [`readable()`] or [`ready()`] is used with this function.

[`readable()`]: Self::readable()
[`ready()`]: Self::ready()

### tokio::try_read_buf (function) › Return

If data is successfully read, `Ok(n)` is returned, where `n` is the
number of bytes read. `Ok(0)` indicates the stream's read half is closed
and will no longer yield data. If the stream is not ready to read data
`Err(io::ErrorKind::WouldBlock)` is returned.

## tokio::try_read_buf (function)

Tries to read data from the stream into the provided buffer, advancing the
buffer's internal cursor, returning how many bytes were read.

Receives any pending data from the socket but does not wait for new data
to arrive. On success, returns the number of bytes read. Because
`try_read_buf()` is non-blocking, the buffer does not have to be stored by
the async task and can exist entirely on the stack.

Usually, [`readable()`] or [`ready()`] is used with this function.

[`readable()`]: TcpStream::readable()
[`ready()`]: TcpStream::ready()

### tokio::try_read_buf (function) › Return

If data is successfully read, `Ok(n)` is returned, where `n` is the
number of bytes read. `Ok(0)` indicates the stream's read half is closed
and will no longer yield data. If the stream is not ready to read data
`Err(io::ErrorKind::WouldBlock)` is returned.

### tokio::try_read_buf (function) › Examples

```no_run
use tokio::net::TcpStream;
use std::error::Error;
use std::io;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // Connect to a peer
    let stream = TcpStream::connect("127.0.0.1:8080").await?;

    loop {
        // Wait for the socket to be readable
        stream.readable().await?;

        let mut buf = Vec::with_capacity(4096);

        // Try to read data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match stream.try_read_buf(&mut buf) {
            Ok(0) => break,
            Ok(n) => {
                println!("read {} bytes", n);
            }
            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    Ok(())
}
```

## tokio::try_read_buf (function)

Tries to read data from the stream into the provided buffer, advancing the
buffer's internal cursor, returning how many bytes were read.

Receives any pending data from the socket but does not wait for new data
to arrive. On success, returns the number of bytes read. Because
`try_read_buf()` is non-blocking, the buffer does not have to be stored by
the async task and can exist entirely on the stack.

Usually, [`readable()`] or [`ready()`] is used with this function.

[`readable()`]: UnixStream::readable()
[`ready()`]: UnixStream::ready()

### tokio::try_read_buf (function) › Return

If data is successfully read, `Ok(n)` is returned, where `n` is the
number of bytes read. `Ok(0)` indicates the stream's read half is closed
and will no longer yield data. If the stream is not ready to read data
`Err(io::ErrorKind::WouldBlock)` is returned.

### tokio::try_read_buf (function) › Examples

```no_run
use tokio::net::UnixStream;
use std::error::Error;
use std::io;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // Connect to a peer
    let dir = tempfile::tempdir().unwrap();
    let bind_path = dir.path().join("bind_path");
    let stream = UnixStream::connect(bind_path).await?;

    loop {
        // Wait for the socket to be readable
        stream.readable().await?;

        let mut buf = Vec::with_capacity(4096);

        // Try to read data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match stream.try_read_buf(&mut buf) {
            Ok(0) => break,
            Ok(n) => {
                println!("read {} bytes", n);
            }
            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    Ok(())
}
```

## tokio::try_read_owned (function)

Attempts to acquire this `RwLock` with shared read access.

If the access couldn't be acquired immediately, returns [`TryLockError`].
Otherwise, an RAII guard is returned which will release read access
when dropped.

This method is identical to [`RwLock::try_read`], except that the
returned guard references the `RwLock` with an [`Arc`] rather than by
borrowing it. Therefore, the `RwLock` must be wrapped in an `Arc` to
call this method, and the guard will live for the `'static` lifetime,
as it keeps the `RwLock` alive by holding an `Arc`.

[`TryLockError`]: TryLockError

### tokio::try_read_owned (function) › Examples

```
use std::sync::Arc;
use tokio::sync::RwLock;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let lock = Arc::new(RwLock::new(1));
let c_lock = lock.clone();

let v = lock.try_read_owned().unwrap();
assert_eq!(*v, 1);

tokio::spawn(async move {
    // While main has an active read lock, we acquire one too.
    let n = c_lock.read_owned().await;
    assert_eq!(*n, 1);
}).await.expect("The spawned task has panicked");

// Drop the guard when spawned task finishes.
drop(v);
# }
```

## tokio::try_read_vectored (function)

Tries to read data from the pipe into the provided buffers, returning
how many bytes were read.

Data is copied to fill each buffer in order, with the final buffer
written to possibly being only partially filled. This method behaves
equivalently to a single call to [`try_read()`] with concatenated
buffers.

Reads any pending data from the pipe but does not wait for new data
to arrive. On success, returns the number of bytes read. Because
`try_read_vectored()` is non-blocking, the buffer does not have to be
stored by the async task and can exist entirely on the stack.

Usually, [`readable()`] is used with this function.

[`try_read()`]: Self::try_read()
[`readable()`]: Self::readable()

### tokio::try_read_vectored (function) › Return

If data is successfully read, `Ok(n)` is returned, where `n` is the
number of bytes read. `Ok(0)` indicates the pipe's writing end is
closed and will no longer write data. If the pipe is not ready to read
data `Err(io::ErrorKind::WouldBlock)` is returned.

### tokio::try_read_vectored (function) › Notes

To avoid unnecessary syscalls, this will only attempt the read
operation if the OS has informed Tokio that this pipe has become
readable. Because of this, `try_read_vectored()` may fail with a
[`WouldBlock`] error if Tokio has not yet heard from the OS that
this pipe has become readable.

### tokio::try_read_vectored (function) › Examples

```no_run
use tokio::net::unix::pipe;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    // Open a reading end of a fifo
    let rx = pipe::OpenOptions::new().open_receiver("path/to/a/fifo")?;

    loop {
        // Wait for the pipe to be readable
        rx.readable().await?;

        // Creating the buffer **after** the `await` prevents it from
        // being stored in the async task.
        let mut buf_a = [0; 512];
        let mut buf_b = [0; 1024];
        let mut bufs = [
            io::IoSliceMut::new(&mut buf_a),
            io::IoSliceMut::new(&mut buf_b),
        ];

        // Try to read data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match rx.try_read_vectored(&mut bufs) {
            Ok(0) => break,
            Ok(n) => {
                println!("read {} bytes", n);
            }
            Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    Ok(())
}
```

[`WouldBlock`]: std::io::ErrorKind::WouldBlock

## tokio::try_read_vectored (function)

Tries to read data from the pipe into the provided buffers, returning
how many bytes were read.

Data is copied to fill each buffer in order, with the final buffer
written to possibly being only partially filled. This method behaves
equivalently to a single call to [`try_read()`] with concatenated
buffers.

Receives any pending data from the pipe but does not wait for new data
to arrive. On success, returns the number of bytes read. Because
`try_read_vectored()` is non-blocking, the buffer does not have to be
stored by the async task and can exist entirely on the stack.

Usually, [`readable()`] or [`ready()`] is used with this function.

[`try_read()`]: NamedPipeClient::try_read()
[`readable()`]: NamedPipeClient::readable()
[`ready()`]: NamedPipeClient::ready()

### tokio::try_read_vectored (function) › Return

If data is successfully read, `Ok(n)` is returned, where `n` is the
number of bytes read. `Ok(0)` indicates the pipe's read half is closed
and will no longer yield data. If the pipe is not ready to read data
`Err(io::ErrorKind::WouldBlock)` is returned.

### tokio::try_read_vectored (function) › Examples

```no_run
use tokio::net::windows::named_pipe;
use std::error::Error;
use std::io::{self, IoSliceMut};

const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-client-try-read-vectored";

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let client = named_pipe::ClientOptions::new().open(PIPE_NAME)?;

    loop {
        // Wait for the pipe to be readable
        client.readable().await?;

        // Creating the buffer **after** the `await` prevents it from
        // being stored in the async task.
        let mut buf_a = [0; 512];
        let mut buf_b = [0; 1024];
        let mut bufs = [
            IoSliceMut::new(&mut buf_a),
            IoSliceMut::new(&mut buf_b),
        ];

        // Try to read data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match client.try_read_vectored(&mut bufs) {
            Ok(0) => break,
            Ok(n) => {
                println!("read {} bytes", n);
            }
            Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    Ok(())
}
```

## tokio::try_read_vectored (function)

Tries to read data from the pipe into the provided buffers, returning
how many bytes were read.

Data is copied to fill each buffer in order, with the final buffer
written to possibly being only partially filled. This method behaves
equivalently to a single call to [`try_read()`] with concatenated
buffers.

Receives any pending data from the pipe but does not wait for new data
to arrive. On success, returns the number of bytes read. Because
`try_read_vectored()` is non-blocking, the buffer does not have to be
stored by the async task and can exist entirely on the stack.

Usually, [`readable()`] or [`ready()`] is used with this function.

[`try_read()`]: NamedPipeServer::try_read()
[`readable()`]: NamedPipeServer::readable()
[`ready()`]: NamedPipeServer::ready()

### tokio::try_read_vectored (function) › Return

If data is successfully read, `Ok(n)` is returned, where `n` is the
number of bytes read. `Ok(0)` indicates the pipe's read half is closed
and will no longer yield data. If the pipe is not ready to read data
`Err(io::ErrorKind::WouldBlock)` is returned.

### tokio::try_read_vectored (function) › Examples

```no_run
use tokio::net::windows::named_pipe;
use std::error::Error;
use std::io::{self, IoSliceMut};

const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-server-try-read-vectored";

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let server = named_pipe::ServerOptions::new()
        .create(PIPE_NAME)?;

    loop {
        // Wait for the pipe to be readable
        server.readable().await?;

        // Creating the buffer **after** the `await` prevents it from
        // being stored in the async task.
        let mut buf_a = [0; 512];
        let mut buf_b = [0; 1024];
        let mut bufs = [
            IoSliceMut::new(&mut buf_a),
            IoSliceMut::new(&mut buf_b),
        ];

        // Try to read data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match server.try_read_vectored(&mut bufs) {
            Ok(0) => break,
            Ok(n) => {
                println!("read {} bytes", n);
            }
            Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    Ok(())
}
```

## tokio::try_read_vectored (function)

Tries to read data from the stream into the provided buffers, returning
how many bytes were read.

Data is copied to fill each buffer in order, with the final buffer
written to possibly being only partially filled. This method behaves
equivalently to a single call to [`try_read()`] with concatenated
buffers.

Receives any pending data from the socket but does not wait for new data
to arrive. On success, returns the number of bytes read. Because
`try_read_vectored()` is non-blocking, the buffer does not have to be
stored by the async task and can exist entirely on the stack.

Usually, [`readable()`] or [`ready()`] is used with this function.

[`try_read()`]: Self::try_read()
[`readable()`]: Self::readable()
[`ready()`]: Self::ready()

### tokio::try_read_vectored (function) › Return

If data is successfully read, `Ok(n)` is returned, where `n` is the
number of bytes read. `Ok(0)` indicates the stream's read half is closed
and will no longer yield data. If the stream is not ready to read data
`Err(io::ErrorKind::WouldBlock)` is returned.

## tokio::try_read_vectored (function)

Tries to read data from the stream into the provided buffers, returning
how many bytes were read.

Data is copied to fill each buffer in order, with the final buffer
written to possibly being only partially filled. This method behaves
equivalently to a single call to [`try_read()`] with concatenated
buffers.

Receives any pending data from the socket but does not wait for new data
to arrive. On success, returns the number of bytes read. Because
`try_read_vectored()` is non-blocking, the buffer does not have to be
stored by the async task and can exist entirely on the stack.

Usually, [`readable()`] or [`ready()`] is used with this function.

[`try_read()`]: Self::try_read()
[`readable()`]: Self::readable()
[`ready()`]: Self::ready()

### tokio::try_read_vectored (function) › Return

If data is successfully read, `Ok(n)` is returned, where `n` is the
number of bytes read. `Ok(0)` indicates the stream's read half is closed
and will no longer yield data. If the stream is not ready to read data
`Err(io::ErrorKind::WouldBlock)` is returned.

## tokio::try_read_vectored (function)

Tries to read data from the stream into the provided buffers, returning
how many bytes were read.

Data is copied to fill each buffer in order, with the final buffer
written to possibly being only partially filled. This method behaves
equivalently to a single call to [`try_read()`] with concatenated
buffers.

Receives any pending data from the socket but does not wait for new data
to arrive. On success, returns the number of bytes read. Because
`try_read_vectored()` is non-blocking, the buffer does not have to be
stored by the async task and can exist entirely on the stack.

Usually, [`readable()`] or [`ready()`] is used with this function.

[`try_read()`]: Self::try_read()
[`readable()`]: Self::readable()
[`ready()`]: Self::ready()

### tokio::try_read_vectored (function) › Return

If data is successfully read, `Ok(n)` is returned, where `n` is the
number of bytes read. `Ok(0)` indicates the stream's read half is closed
and will no longer yield data. If the stream is not ready to read data
`Err(io::ErrorKind::WouldBlock)` is returned.

## tokio::try_read_vectored (function)

Tries to read data from the stream into the provided buffers, returning
how many bytes were read.

Data is copied to fill each buffer in order, with the final buffer
written to possibly being only partially filled. This method behaves
equivalently to a single call to [`try_read()`] with concatenated
buffers.

Receives any pending data from the socket but does not wait for new data
to arrive. On success, returns the number of bytes read. Because
`try_read_vectored()` is non-blocking, the buffer does not have to be
stored by the async task and can exist entirely on the stack.

Usually, [`readable()`] or [`ready()`] is used with this function.

[`try_read()`]: Self::try_read()
[`readable()`]: Self::readable()
[`ready()`]: Self::ready()

### tokio::try_read_vectored (function) › Return

If data is successfully read, `Ok(n)` is returned, where `n` is the
number of bytes read. `Ok(0)` indicates the stream's read half is closed
and will no longer yield data. If the stream is not ready to read data
`Err(io::ErrorKind::WouldBlock)` is returned.

## tokio::try_read_vectored (function)

Tries to read data from the stream into the provided buffers, returning
how many bytes were read.

Data is copied to fill each buffer in order, with the final buffer
written to possibly being only partially filled. This method behaves
equivalently to a single call to [`try_read()`] with concatenated
buffers.

Receives any pending data from the socket but does not wait for new data
to arrive. On success, returns the number of bytes read. Because
`try_read_vectored()` is non-blocking, the buffer does not have to be
stored by the async task and can exist entirely on the stack.

Usually, [`readable()`] or [`ready()`] is used with this function.

[`try_read()`]: TcpStream::try_read()
[`readable()`]: TcpStream::readable()
[`ready()`]: TcpStream::ready()

### tokio::try_read_vectored (function) › Return

If data is successfully read, `Ok(n)` is returned, where `n` is the
number of bytes read. `Ok(0)` indicates the stream's read half is closed
and will no longer yield data. If the stream is not ready to read data
`Err(io::ErrorKind::WouldBlock)` is returned.

### tokio::try_read_vectored (function) › Examples

```no_run
use tokio::net::TcpStream;
use std::error::Error;
use std::io::{self, IoSliceMut};

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // Connect to a peer
    let stream = TcpStream::connect("127.0.0.1:8080").await?;

    loop {
        // Wait for the socket to be readable
        stream.readable().await?;

        // Creating the buffer **after** the `await` prevents it from
        // being stored in the async task.
        let mut buf_a = [0; 512];
        let mut buf_b = [0; 1024];
        let mut bufs = [
            IoSliceMut::new(&mut buf_a),
            IoSliceMut::new(&mut buf_b),
        ];

        // Try to read data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match stream.try_read_vectored(&mut bufs) {
            Ok(0) => break,
            Ok(n) => {
                println!("read {} bytes", n);
            }
            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    Ok(())
}
```

## tokio::try_read_vectored (function)

Tries to read data from the stream into the provided buffers, returning
how many bytes were read.

Data is copied to fill each buffer in order, with the final buffer
written to possibly being only partially filled. This method behaves
equivalently to a single call to [`try_read()`] with concatenated
buffers.

Receives any pending data from the socket but does not wait for new data
to arrive. On success, returns the number of bytes read. Because
`try_read_vectored()` is non-blocking, the buffer does not have to be
stored by the async task and can exist entirely on the stack.

Usually, [`readable()`] or [`ready()`] is used with this function.

[`try_read()`]: UnixStream::try_read()
[`readable()`]: UnixStream::readable()
[`ready()`]: UnixStream::ready()

### tokio::try_read_vectored (function) › Return

If data is successfully read, `Ok(n)` is returned, where `n` is the
number of bytes read. `Ok(0)` indicates the stream's read half is closed
and will no longer yield data. If the stream is not ready to read data
`Err(io::ErrorKind::WouldBlock)` is returned.

### tokio::try_read_vectored (function) › Examples

```no_run
use tokio::net::UnixStream;
use std::error::Error;
use std::io::{self, IoSliceMut};

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // Connect to a peer
    let dir = tempfile::tempdir().unwrap();
    let bind_path = dir.path().join("bind_path");
    let stream = UnixStream::connect(bind_path).await?;

    loop {
        // Wait for the socket to be readable
        stream.readable().await?;

        // Creating the buffer **after** the `await` prevents it from
        // being stored in the async task.
        let mut buf_a = [0; 512];
        let mut buf_b = [0; 1024];
        let mut bufs = [
            IoSliceMut::new(&mut buf_a),
            IoSliceMut::new(&mut buf_b),
        ];

        // Try to read data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match stream.try_read_vectored(&mut bufs) {
            Ok(0) => break,
            Ok(n) => {
                println!("read {} bytes", n);
            }
            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    Ok(())
}
```

## tokio::try_recv (function)

Attempts to receive a value.

If a pending value exists in the channel, it is returned. If no value
has been sent, the current task **will not** be registered for
future notification.

This function is useful to call from outside the context of an
asynchronous task.

Note that unlike the `poll` method, the `try_recv` method cannot fail
spuriously. Any send or close event that happens before this call to
`try_recv` will be correctly returned to the caller.

### tokio::try_recv (function) › Return

- `Ok(T)` if a value is pending in the channel.
- `Err(TryRecvError::Empty)` if no value has been sent yet.
- `Err(TryRecvError::Closed)` if the sender has dropped without sending
  a value, or if the message has already been received.

### tokio::try_recv (function) › Examples

`try_recv` before a value is sent, then after.

```
use tokio::sync::oneshot;
use tokio::sync::oneshot::error::TryRecvError;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = oneshot::channel();

match rx.try_recv() {
    // The channel is currently empty
    Err(TryRecvError::Empty) => {}
    _ => unreachable!(),
}

// Send a value
tx.send("hello").unwrap();

match rx.try_recv() {
     Ok(value) => assert_eq!(value, "hello"),
     _ => unreachable!(),
}
# }
```

`try_recv` when the sender dropped before sending a value

```
use tokio::sync::oneshot;
use tokio::sync::oneshot::error::TryRecvError;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = oneshot::channel::<()>();

drop(tx);

match rx.try_recv() {
    // The channel will never receive a value.
    Err(TryRecvError::Closed) => {}
    _ => unreachable!(),
}
# }
```

## tokio::try_recv (function)

Attempts to return a pending value on this receiver without awaiting.

This is useful for a flavor of "optimistic check" before deciding to
await on a receiver.

Compared with [`recv`], this function has three failure cases instead of two
(one for closed, one for an empty buffer, one for a lagging receiver).

`Err(TryRecvError::Closed)` is returned when all `Sender` halves have
dropped, indicating that no further values can be sent on the channel.

If the [`Receiver`] handle falls behind, once the channel is full, newly
sent values overwrite old values in the ring buffer. The next call to
[`try_recv`] then returns `Err(TryRecvError::Lagged(n))`, where `n` is
the number of overwritten messages the receiver missed. The receiver
stays subscribed; its internal cursor is advanced to the oldest value
still held by the channel. A subsequent call to [`try_recv`] returns
that value, unless further sends overwrite it before the receiver reads
it. If there are no values to receive, `Err(TryRecvError::Empty)` is
returned. See [lagging](self#lagging) for details.

[`recv`]: crate::sync::broadcast::Receiver::recv
[`try_recv`]: crate::sync::broadcast::Receiver::try_recv
[`Receiver`]: crate::sync::broadcast::Receiver

### tokio::try_recv (function) › Examples

```
use tokio::sync::broadcast;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = broadcast::channel(16);

assert!(rx.try_recv().is_err());

tx.send(10).unwrap();

let value = rx.try_recv().unwrap();
assert_eq!(10, value);
# }
```

## tokio::try_recv (function)

Tries to receive a single datagram message on the socket from the remote
address to which it is connected. On success, returns the number of
bytes read.

This method must be called with valid byte array `buf` of sufficient size
to hold the message bytes. If a message is too long to fit in the
supplied buffer, excess bytes may be discarded.

When there is no pending data, `Err(io::ErrorKind::WouldBlock)` is
returned. This function is usually paired with `readable()`.

### tokio::try_recv (function) › Examples

```no_run
use tokio::net::UdpSocket;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    // Connect to a peer
    let socket = UdpSocket::bind("127.0.0.1:8080").await?;
    socket.connect("127.0.0.1:8081").await?;

    loop {
        // Wait for the socket to be readable
        socket.readable().await?;

        // The buffer is **not** included in the async task and will
        // only exist on the stack.
        let mut buf = [0; 1024];

        // Try to recv data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match socket.try_recv(&mut buf) {
            Ok(n) => {
                println!("GOT {:?}", &buf[..n]);
                break;
            }
            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e);
            }
        }
    }

    Ok(())
}
```

## tokio::try_recv (function)

Tries to receive the next value for this receiver.

This method returns the [`Empty`] error if the channel is currently
empty, but there are still outstanding [senders] or [permits].

This method returns the [`Disconnected`] error if the channel is
currently empty, and there are no outstanding [senders] or [permits].

Unlike the [`poll_recv`] method, this method will never return an
[`Empty`] error spuriously.

[`Empty`]: crate::sync::mpsc::error::TryRecvError::Empty
[`Disconnected`]: crate::sync::mpsc::error::TryRecvError::Disconnected
[`poll_recv`]: Self::poll_recv
[senders]: crate::sync::mpsc::Sender
[permits]: crate::sync::mpsc::Permit

### tokio::try_recv (function) › Examples

```
use tokio::sync::mpsc;
use tokio::sync::mpsc::error::TryRecvError;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = mpsc::channel(100);

tx.send("hello").await.unwrap();

assert_eq!(Ok("hello"), rx.try_recv());
assert_eq!(Err(TryRecvError::Empty), rx.try_recv());

tx.send("hello").await.unwrap();
// Drop the last sender, closing the channel.
drop(tx);

assert_eq!(Ok("hello"), rx.try_recv());
assert_eq!(Err(TryRecvError::Disconnected), rx.try_recv());
# }
```

## tokio::try_recv (function)

Tries to receive the next value for this receiver.

This method returns the [`Empty`] error if the channel is currently
empty, but there are still outstanding [senders] or [permits].

This method returns the [`Disconnected`] error if the channel is
currently empty, and there are no outstanding [senders] or [permits].

Unlike the [`poll_recv`] method, this method will never return an
[`Empty`] error spuriously.

[`Empty`]: crate::sync::mpsc::error::TryRecvError::Empty
[`Disconnected`]: crate::sync::mpsc::error::TryRecvError::Disconnected
[`poll_recv`]: Self::poll_recv
[senders]: crate::sync::mpsc::Sender
[permits]: crate::sync::mpsc::Permit

### tokio::try_recv (function) › Examples

```
use tokio::sync::mpsc;
use tokio::sync::mpsc::error::TryRecvError;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = mpsc::unbounded_channel();

tx.send("hello").unwrap();

assert_eq!(Ok("hello"), rx.try_recv());
assert_eq!(Err(TryRecvError::Empty), rx.try_recv());

tx.send("hello").unwrap();
// Drop the last sender, closing the channel.
drop(tx);

assert_eq!(Ok("hello"), rx.try_recv());
assert_eq!(Err(TryRecvError::Disconnected), rx.try_recv());
# }
```

## tokio::try_recv_buf (function)

Tries to receive data from the stream into the provided buffer, advancing the
buffer's internal cursor, returning how many bytes were read.

This method must be called with valid byte array `buf` of sufficient size
to hold the message bytes. If a message is too long to fit in the
supplied buffer, excess bytes may be discarded.

This method can be used even if `buf` is uninitialized.

When there is no pending data, `Err(io::ErrorKind::WouldBlock)` is
returned. This function is usually paired with `readable()`.

### tokio::try_recv_buf (function) › Examples

```no_run
use tokio::net::UdpSocket;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    // Connect to a peer
    let socket = UdpSocket::bind("127.0.0.1:8080").await?;
    socket.connect("127.0.0.1:8081").await?;

    loop {
        // Wait for the socket to be readable
        socket.readable().await?;

        let mut buf = Vec::with_capacity(1024);

        // Try to recv data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match socket.try_recv_buf(&mut buf) {
            Ok(n) => {
                println!("GOT {:?}", &buf[..n]);
                break;
            }
            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e);
            }
        }
    }

    Ok(())
}
```

## tokio::try_recv_buf_from (function)

Tries to receive a single datagram message on the socket. On success,
returns the number of bytes read and the origin.

This method must be called with valid byte array `buf` of sufficient size
to hold the message bytes. If a message is too long to fit in the
supplied buffer, excess bytes may be discarded.

This method can be used even if `buf` is uninitialized.

When there is no pending data, `Err(io::ErrorKind::WouldBlock)` is
returned. This function is usually paired with `readable()`.

### tokio::try_recv_buf_from (function) › Notes
Note that the socket address **cannot** be implicitly trusted, because it is relatively
trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
Because UDP is stateless and does not validate the origin of a packet,
the attacker does not need to be able to intercept traffic in order to interfere.
It is important to be aware of this when designing your application-level protocol.

[packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection

### tokio::try_recv_buf_from (function) › Examples

```no_run
use tokio::net::UdpSocket;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    // Connect to a peer
    let socket = UdpSocket::bind("127.0.0.1:8080").await?;

    loop {
        // Wait for the socket to be readable
        socket.readable().await?;

        let mut buf = Vec::with_capacity(1024);

        // Try to recv data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match socket.try_recv_buf_from(&mut buf) {
            Ok((n, _addr)) => {
                println!("GOT {:?}", &buf[..n]);
                break;
            }
            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e);
            }
        }
    }

    Ok(())
}
```

## tokio::try_recv_from (function)

Tries to receive a single datagram message on the socket. On success,
returns the number of bytes read and the origin.

This method must be called with valid byte array `buf` of sufficient size
to hold the message bytes. If a message is too long to fit in the
supplied buffer, excess bytes may be discarded.

When there is no pending data, `Err(io::ErrorKind::WouldBlock)` is
returned. This function is usually paired with `readable()`.

### tokio::try_recv_from (function) › Notes

Note that the socket address **cannot** be implicitly trusted, because it is relatively
trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
Because UDP is stateless and does not validate the origin of a packet,
the attacker does not need to be able to intercept traffic in order to interfere.
It is important to be aware of this when designing your application-level protocol.

[packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection

### tokio::try_recv_from (function) › Examples

```no_run
use tokio::net::UdpSocket;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    // Connect to a peer
    let socket = UdpSocket::bind("127.0.0.1:8080").await?;

    loop {
        // Wait for the socket to be readable
        socket.readable().await?;

        // The buffer is **not** included in the async task and will
        // only exist on the stack.
        let mut buf = [0; 1024];

        // Try to recv data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match socket.try_recv_from(&mut buf) {
            Ok((n, _addr)) => {
                println!("GOT {:?}", &buf[..n]);
                break;
            }
            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e);
            }
        }
    }

    Ok(())
}
```

## tokio::try_reserve (function)

Tries to acquire a slot in the channel without waiting for the slot to become
available.

If the channel is full this function will return [`TrySendError`], otherwise
if there is a slot available it will return a [`Permit`] that will then allow you
to [`send`] on the channel with a guaranteed slot. This function is similar to
[`reserve`] except it does not await for the slot to become available.

Dropping [`Permit`] without sending a message releases the capacity back
to the channel.

[`Permit`]: Permit
[`send`]: Permit::send
[`reserve`]: Sender::reserve

### tokio::try_reserve (function) › Examples

```
use tokio::sync::mpsc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = mpsc::channel(1);

// Reserve capacity
let permit = tx.try_reserve().unwrap();

// Trying to send directly on the `tx` will fail due to no
// available capacity.
assert!(tx.try_send(123).is_err());

// Trying to reserve an additional slot on the `tx` will
// fail because there is no capacity.
assert!(tx.try_reserve().is_err());

// Sending on the permit succeeds
permit.send(456);

// The value sent on the permit is received
assert_eq!(rx.recv().await.unwrap(), 456);

# }
```

## tokio::try_reserve_many (function)

Tries to acquire `n` slots in the channel without waiting for the slot to become
available.

A [`PermitIterator`] is returned to track the reserved capacity.
You can call this [`Iterator`] until it is exhausted to
get a [`Permit`] and then call [`Permit::send`]. This function is similar to
[`reserve_many`] except it does not await for the slots to become available.

If there are fewer than `n` permits available on the channel, then
this function will return a [`TrySendError::Full`]. If the channel is closed
this function will return a [`TrySendError::Closed`].

Dropping [`PermitIterator`] without consuming it entirely releases the remaining
permits back to the channel.

[`PermitIterator`]: PermitIterator
[`send`]: Permit::send
[`reserve_many`]: Sender::reserve_many

### tokio::try_reserve_many (function) › Examples

```
use tokio::sync::mpsc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = mpsc::channel(2);

// Reserve capacity
let mut permit = tx.try_reserve_many(2).unwrap();

// Trying to send directly on the `tx` will fail due to no
// available capacity.
assert!(tx.try_send(123).is_err());

// Trying to reserve an additional slot on the `tx` will
// fail because there is no capacity.
assert!(tx.try_reserve().is_err());

// Sending with the permit iterator succeeds
permit.next().unwrap().send(456);
permit.next().unwrap().send(457);

// The iterator should now be exhausted
assert!(permit.next().is_none());

// The value sent on the permit is received
assert_eq!(rx.recv().await.unwrap(), 456);
assert_eq!(rx.recv().await.unwrap(), 457);

// Trying to call try_reserve_many with 0 will return an empty iterator
let mut permit = tx.try_reserve_many(0).unwrap();
assert!(permit.next().is_none());

// Trying to call try_reserve_many with a number greater than the channel
// capacity will return an error
let permit = tx.try_reserve_many(3);
assert!(permit.is_err());

// Trying to call try_reserve_many on a closed channel will return an error
drop(rx);
let permit = tx.try_reserve_many(1);
assert!(permit.is_err());

let permit = tx.try_reserve_many(0);
assert!(permit.is_err());
# }
```

## tokio::try_reserve_owned (function)

Tries to acquire a slot in the channel without waiting for the slot to become
available, returning an owned permit.

This moves the sender _by value_, and returns an owned permit that can
be used to send a message into the channel. Unlike [`Sender::try_reserve`],
this method may be used in cases where the permit must be valid for the
`'static` lifetime.  `Sender`s may be cloned cheaply (`Sender::clone` is
essentially a reference count increment, comparable to [`Arc::clone`]),
so when multiple [`OwnedPermit`]s are needed or the `Sender` cannot be
moved, it can be cloned prior to calling `try_reserve_owned`.

If the channel is full this function will return a [`TrySendError`].
Since the sender is taken by value, the `TrySendError` returned in this
case contains the sender, so that it may be used again. Otherwise, if
there is a slot available, this method will return an [`OwnedPermit`]
that can then be used to [`send`] on the channel with a guaranteed slot.
This function is similar to  [`reserve_owned`] except it does not await
for the slot to become available.

Dropping the [`OwnedPermit`] without sending a message releases the capacity back
to the channel.

[`OwnedPermit`]: OwnedPermit
[`send`]: OwnedPermit::send
[`reserve_owned`]: Sender::reserve_owned
[`Arc::clone`]: std::sync::Arc::clone

### tokio::try_reserve_owned (function) › Examples

```
use tokio::sync::mpsc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let (tx, mut rx) = mpsc::channel(1);

// Reserve capacity
let permit = tx.clone().try_reserve_owned().unwrap();

// Trying to send directly on the `tx` will fail due to no
// available capacity.
assert!(tx.try_send(123).is_err());

// Trying to reserve an additional slot on the `tx` will
// fail because there is no capacity.
assert!(tx.try_reserve().is_err());

// Sending on the permit succeeds
permit.send(456);

// The value sent on the permit is received
assert_eq!(rx.recv().await.unwrap(), 456);

# }
```

## tokio::try_send (function)

Attempts to immediately send a message on this `Sender`.

This method differs from [`send`] by returning immediately if the channel's
buffer is full or no receiver is waiting to acquire some data. Compared
with [`send`], this function has two failure cases instead of one (one for
disconnection, one for a full buffer).

### tokio::try_send (function) › Errors

If the channel capacity has been reached, i.e., the channel has `n`
buffered values where `n` is the argument passed to [`channel`], then an
error is returned.

If the receive half of the channel is closed, either due to [`close`]
being called or the [`Receiver`] handle dropping, the function returns
an error. The error includes the value passed to `send`.

[`send`]: Sender::send
[`channel`]: channel
[`close`]: Receiver::close

### tokio::try_send (function) › Examples

```
use tokio::sync::mpsc;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
// Create a channel with buffer size 1
let (tx1, mut rx) = mpsc::channel(1);
let tx2 = tx1.clone();

tokio::spawn(async move {
    tx1.send(1).await.unwrap();
    tx1.send(2).await.unwrap();
    // task waits until the receiver receives a value.
});

tokio::spawn(async move {
    // This will return an error and send
    // no message if the buffer is full
    let _ = tx2.try_send(3);
});

let mut msg;
msg = rx.recv().await.unwrap();
println!("message {} received", msg);

msg = rx.recv().await.unwrap();
println!("message {} received", msg);

// Third message may have never been sent
match rx.recv().await {
    Some(msg) => println!("message {} received", msg),
    None => println!("the third message was never sent"),
}
# }
```

## tokio::try_send (function)

Tries to send data on the socket to the remote address to which it is
connected.

When the socket buffer is full, `Err(io::ErrorKind::WouldBlock)` is
returned. This function is usually paired with `writable()`.

### tokio::try_send (function) › Returns

If successful, `Ok(n)` is returned, where `n` is the number of bytes
sent. If the socket is not ready to send data,
`Err(ErrorKind::WouldBlock)` is returned.

### tokio::try_send (function) › Examples

```no_run
use tokio::net::UdpSocket;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    // Bind a UDP socket
    let socket = UdpSocket::bind("127.0.0.1:8080").await?;

    // Connect to a peer
    socket.connect("127.0.0.1:8081").await?;

    loop {
        // Wait for the socket to be writable
        socket.writable().await?;

        // Try to send data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match socket.try_send(b"hello world") {
            Ok(n) => {
                break;
            }
            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e);
            }
        }
    }

    Ok(())
}
```

## tokio::try_send_to (function)

Tries to send data on the socket to the given address, but if the send is
blocked this will return right away.

This function is usually paired with `writable()`.

### tokio::try_send_to (function) › Returns

If successful, returns the number of bytes sent

Users should ensure that when the remote cannot receive, the
[`ErrorKind::WouldBlock`] is properly handled. An error can also occur
if the IP version of the socket does not match that of `target`.

[`ErrorKind::WouldBlock`]: std::io::ErrorKind::WouldBlock

### tokio::try_send_to (function) › Example

```no_run
use tokio::net::UdpSocket;
use std::error::Error;
use std::io;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let socket = UdpSocket::bind("127.0.0.1:8080").await?;

    let dst = "127.0.0.1:8081".parse()?;

    loop {
        socket.writable().await?;

        match socket.try_send_to(&b"hello world"[..], dst) {
            Ok(sent) => {
                println!("sent {} bytes", sent);
                break;
            }
            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                // Writable false positive.
                continue;
            }
            Err(e) => return Err(e.into()),
        }
    }

    Ok(())
}
```

## tokio::try_wait (function)

Attempts to collect the exit status of the child if it has already
exited.

This function will not block the calling thread and will only
check to see if the child process has exited or not. If the child has
exited then on Unix the process ID is reaped. This function is
guaranteed to repeatedly return a successful exit status so long as the
child has already exited.

If the child has exited, then `Ok(Some(status))` is returned. If the
exit status is not available at this time then `Ok(None)` is returned.
If an error occurs, then that error is returned.

Note that unlike `wait`, this function will not attempt to drop stdin,
nor will it wake the current task if the child exits.

## tokio::try_with (function)

Accesses the current task-local and runs the provided closure.

If the task-local with the associated key is not present, this
method will return an `AccessError`. For a panicking variant,
see `with`.

## tokio::try_with_interest (function)

Creates an [`AsyncFd`] backed by (and taking ownership of) an object
implementing [`AsRawFd`], with a specific [`Interest`]. The backing
file descriptor is cached at the time of creation.

In the case of failure, it returns [`AsyncFdTryNewError`] that contains the original object
passed to this function.

### tokio::try_with_interest (function) › Panics

This function panics if there is no current reactor set, or if the `rt`
feature flag is not enabled.

## tokio::try_write (function)

Attempts to acquire this `RwLock` with exclusive write access.

If the access couldn't be acquired immediately, returns [`TryLockError`].
Otherwise, an RAII guard is returned which will release write access
when dropped.

[`TryLockError`]: TryLockError

### tokio::try_write (function) › Examples

```
use tokio::sync::RwLock;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let rw = RwLock::new(1);

let v = rw.read().await;
assert_eq!(*v, 1);

assert!(rw.try_write().is_err());
# }
```

## tokio::try_write (function)

Tries to write a buffer to the pipe, returning how many bytes were
written.

The function will attempt to write the entire contents of `buf`, but
only part of the buffer may be written.

This function is usually paired with `writable()`.

### tokio::try_write (function) › Return

If data is successfully written, `Ok(n)` is returned, where `n` is the
number of bytes written. If the pipe is not ready to write data,
`Err(io::ErrorKind::WouldBlock)` is returned.

### tokio::try_write (function) › Examples

```no_run
use tokio::net::windows::named_pipe;
use std::error::Error;
use std::io;

const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-client-try-write";

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let client = named_pipe::ClientOptions::new().open(PIPE_NAME)?;

    loop {
        // Wait for the pipe to be writable
        client.writable().await?;

        // Try to write data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match client.try_write(b"hello world") {
            Ok(n) => {
                break;
            }
            Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    Ok(())
}
```

## tokio::try_write (function)

Tries to write a buffer to the pipe, returning how many bytes were
written.

The function will attempt to write the entire contents of `buf`, but
only part of the buffer may be written.

This function is usually paired with `writable()`.

### tokio::try_write (function) › Return

If data is successfully written, `Ok(n)` is returned, where `n` is the
number of bytes written. If the pipe is not ready to write data,
`Err(io::ErrorKind::WouldBlock)` is returned.

### tokio::try_write (function) › Examples

```no_run
use tokio::net::windows::named_pipe;
use std::error::Error;
use std::io;

const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-server-try-write";

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let server = named_pipe::ServerOptions::new()
        .create(PIPE_NAME)?;

    loop {
        // Wait for the pipe to be writable
        server.writable().await?;

        // Try to write data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match server.try_write(b"hello world") {
            Ok(n) => {
                break;
            }
            Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    Ok(())
}
```

## tokio::try_write (function)

Tries to write a buffer to the pipe, returning how many bytes were
written.

The function will attempt to write the entire contents of `buf`, but
only part of the buffer may be written. If the length of `buf` is not
greater than `PIPE_BUF` (an OS constant, 4096 under Linux), then the
write is guaranteed to be atomic, i.e. either the entire content of
`buf` will be written or this method will fail with `WouldBlock`. There
is no such guarantee if `buf` is larger than `PIPE_BUF`.

This function is usually paired with [`writable`].

[`writable`]: Self::writable

### tokio::try_write (function) › Return

If data is successfully written, `Ok(n)` is returned, where `n` is the
number of bytes written. If the pipe is not ready to write data,
`Err(io::ErrorKind::WouldBlock)` is returned.

### tokio::try_write (function) › Notes

To avoid unnecessary syscalls, this will only attempt the write
operation if the OS has informed Tokio that this pipe has become
writable. Because of this, `try_write()` may fail with a
[`WouldBlock`] error if Tokio has not yet heard from the OS that
this pipe has become writable.

### tokio::try_write (function) › Examples

```no_run
use tokio::net::unix::pipe;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    // Open a writing end of a fifo
    let tx = pipe::OpenOptions::new().open_sender("path/to/a/fifo")?;

    loop {
        // Wait for the pipe to be writable
        tx.writable().await?;

        // Try to write data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match tx.try_write(b"hello world") {
            Ok(n) => {
                break;
            }
            Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    Ok(())
}
```

[`WouldBlock`]: std::io::ErrorKind::WouldBlock

## tokio::try_write (function)

Tries to write a buffer to the stream, returning how many bytes were
written.

The function will attempt to write the entire contents of `buf`, but
only part of the buffer may be written.

This function is usually paired with `writable()`.

### tokio::try_write (function) › Return

If data is successfully written, `Ok(n)` is returned, where `n` is the
number of bytes written. If the stream is not ready to write data,
`Err(io::ErrorKind::WouldBlock)` is returned.

## tokio::try_write (function)

Tries to write a buffer to the stream, returning how many bytes were
written.

The function will attempt to write the entire contents of `buf`, but
only part of the buffer may be written.

This function is usually paired with `writable()`.

### tokio::try_write (function) › Return

If data is successfully written, `Ok(n)` is returned, where `n` is the
number of bytes written. If the stream is not ready to write data,
`Err(io::ErrorKind::WouldBlock)` is returned.

## tokio::try_write (function)

Tries to write a buffer to the stream, returning how many bytes were
written.

The function will attempt to write the entire contents of `buf`, but
only part of the buffer may be written.

This function is usually paired with `writable()`.

### tokio::try_write (function) › Return

If data is successfully written, `Ok(n)` is returned, where `n` is the
number of bytes written. If the stream is not ready to write data,
`Err(io::ErrorKind::WouldBlock)` is returned.

## tokio::try_write (function)

Tries to write a buffer to the stream, returning how many bytes were
written.

The function will attempt to write the entire contents of `buf`, but
only part of the buffer may be written.

This function is usually paired with `writable()`.

### tokio::try_write (function) › Return

If data is successfully written, `Ok(n)` is returned, where `n` is the
number of bytes written. If the stream is not ready to write data,
`Err(io::ErrorKind::WouldBlock)` is returned.

## tokio::try_write (function)

Tries to write a buffer to the stream, returning how many bytes were
written.

The function will attempt to write the entire contents of `buf`, but
only part of the buffer may be written.

This function is usually paired with `writable()`.

### tokio::try_write (function) › Return

If data is successfully written, `Ok(n)` is returned, where `n` is the
number of bytes written. If the stream is not ready to write data,
`Err(io::ErrorKind::WouldBlock)` is returned.

### tokio::try_write (function) › Examples

```no_run
use tokio::net::UnixStream;
use std::error::Error;
use std::io;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // Connect to a peer
    let dir = tempfile::tempdir().unwrap();
    let bind_path = dir.path().join("bind_path");
    let stream = UnixStream::connect(bind_path).await?;

    loop {
        // Wait for the socket to be writable
        stream.writable().await?;

        // Try to write data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match stream.try_write(b"hello world") {
            Ok(n) => {
                break;
            }
            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    Ok(())
}
```

## tokio::try_write (function)

Try to write a buffer to the stream, returning how many bytes were
written.

The function will attempt to write the entire contents of `buf`, but
only part of the buffer may be written.

This function is usually paired with `writable()`.

### tokio::try_write (function) › Return

If data is successfully written, `Ok(n)` is returned, where `n` is the
number of bytes written. If the stream is not ready to write data,
`Err(io::ErrorKind::WouldBlock)` is returned.

### tokio::try_write (function) › Examples

```no_run
use tokio::net::TcpStream;
use std::error::Error;
use std::io;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // Connect to a peer
    let stream = TcpStream::connect("127.0.0.1:8080").await?;

    loop {
        // Wait for the socket to be writable
        stream.writable().await?;

        // Try to write data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match stream.try_write(b"hello world") {
            Ok(n) => {
                break;
            }
            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    Ok(())
}
```

## tokio::try_write_owned (function)

Attempts to acquire this `RwLock` with exclusive write access.

If the access couldn't be acquired immediately, returns [`TryLockError`].
Otherwise, an RAII guard is returned which will release write access
when dropped.

This method is identical to [`RwLock::try_write`], except that the
returned guard references the `RwLock` with an [`Arc`] rather than by
borrowing it. Therefore, the `RwLock` must be wrapped in an `Arc` to
call this method, and the guard will live for the `'static` lifetime,
as it keeps the `RwLock` alive by holding an `Arc`.

[`TryLockError`]: TryLockError

### tokio::try_write_owned (function) › Examples

```
use std::sync::Arc;
use tokio::sync::RwLock;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let rw = Arc::new(RwLock::new(1));

let v = Arc::clone(&rw).read_owned().await;
assert_eq!(*v, 1);

assert!(rw.try_write_owned().is_err());
# }
```

## tokio::try_write_vectored (function)

Tries to write several buffers to the pipe, returning how many bytes
were written.

Data is written from each buffer in order, with the final buffer read
from possible being only partially consumed. This method behaves
equivalently to a single call to [`try_write()`] with concatenated
buffers.

If the total length of buffers is not greater than `PIPE_BUF` (an OS
constant, 4096 under Linux), then the write is guaranteed to be atomic,
i.e. either the entire contents of buffers will be written or this
method will fail with `WouldBlock`. There is no such guarantee if the
total length of buffers is greater than `PIPE_BUF`.

This function is usually paired with [`writable`].

[`try_write()`]: Self::try_write()
[`writable`]: Self::writable

### tokio::try_write_vectored (function) › Return

If data is successfully written, `Ok(n)` is returned, where `n` is the
number of bytes written. If the pipe is not ready to write data,
`Err(io::ErrorKind::WouldBlock)` is returned.

### tokio::try_write_vectored (function) › Notes

To avoid unnecessary syscalls, this will only attempt the write
operation if the OS has informed Tokio that this pipe has become
writable. Because of this, `try_write_vectored()` may fail with a
[`WouldBlock`] error if Tokio has not yet heard from the OS that
this pipe has become writable.

### tokio::try_write_vectored (function) › Examples

```no_run
use tokio::net::unix::pipe;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    // Open a writing end of a fifo
    let tx = pipe::OpenOptions::new().open_sender("path/to/a/fifo")?;

    let bufs = [io::IoSlice::new(b"hello "), io::IoSlice::new(b"world")];

    loop {
        // Wait for the pipe to be writable
        tx.writable().await?;

        // Try to write data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match tx.try_write_vectored(&bufs) {
            Ok(n) => {
                break;
            }
            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    Ok(())
}
```

[`WouldBlock`]: std::io::ErrorKind::WouldBlock

## tokio::try_write_vectored (function)

Tries to write several buffers to the pipe, returning how many bytes
were written.

Data is written from each buffer in order, with the final buffer read
from possible being only partially consumed. This method behaves
equivalently to a single call to [`try_write()`] with concatenated
buffers.

This function is usually paired with `writable()`.

[`try_write()`]: NamedPipeClient::try_write()

### tokio::try_write_vectored (function) › Return

If data is successfully written, `Ok(n)` is returned, where `n` is the
number of bytes written. If the pipe is not ready to write data,
`Err(io::ErrorKind::WouldBlock)` is returned.

### tokio::try_write_vectored (function) › Examples

```no_run
use tokio::net::windows::named_pipe;
use std::error::Error;
use std::io;

const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-client-try-write-vectored";

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let client = named_pipe::ClientOptions::new().open(PIPE_NAME)?;

    let bufs = [io::IoSlice::new(b"hello "), io::IoSlice::new(b"world")];

    loop {
        // Wait for the pipe to be writable
        client.writable().await?;

        // Try to write data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match client.try_write_vectored(&bufs) {
            Ok(n) => {
                break;
            }
            Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    Ok(())
}
```

## tokio::try_write_vectored (function)

Tries to write several buffers to the pipe, returning how many bytes
were written.

Data is written from each buffer in order, with the final buffer read
from possible being only partially consumed. This method behaves
equivalently to a single call to [`try_write()`] with concatenated
buffers.

This function is usually paired with `writable()`.

[`try_write()`]: NamedPipeServer::try_write()

### tokio::try_write_vectored (function) › Return

If data is successfully written, `Ok(n)` is returned, where `n` is the
number of bytes written. If the pipe is not ready to write data,
`Err(io::ErrorKind::WouldBlock)` is returned.

### tokio::try_write_vectored (function) › Examples

```no_run
use tokio::net::windows::named_pipe;
use std::error::Error;
use std::io;

const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-server-try-write-vectored";

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let server = named_pipe::ServerOptions::new()
        .create(PIPE_NAME)?;

    let bufs = [io::IoSlice::new(b"hello "), io::IoSlice::new(b"world")];

    loop {
        // Wait for the pipe to be writable
        server.writable().await?;

        // Try to write data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match server.try_write_vectored(&bufs) {
            Ok(n) => {
                break;
            }
            Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    Ok(())
}
```

## tokio::try_write_vectored (function)

Tries to write several buffers to the stream, returning how many bytes
were written.

Data is written from each buffer in order, with the final buffer read
from possible being only partially consumed. This method behaves
equivalently to a single call to [`try_write()`] with concatenated
buffers.

This function is usually paired with `writable()`.

[`try_write()`]: Self::try_write()

### tokio::try_write_vectored (function) › Return

If data is successfully written, `Ok(n)` is returned, where `n` is the
number of bytes written. If the stream is not ready to write data,
`Err(io::ErrorKind::WouldBlock)` is returned.

## tokio::try_write_vectored (function)

Tries to write several buffers to the stream, returning how many bytes
were written.

Data is written from each buffer in order, with the final buffer read
from possible being only partially consumed. This method behaves
equivalently to a single call to [`try_write()`] with concatenated
buffers.

This function is usually paired with `writable()`.

[`try_write()`]: Self::try_write()

### tokio::try_write_vectored (function) › Return

If data is successfully written, `Ok(n)` is returned, where `n` is the
number of bytes written. If the stream is not ready to write data,
`Err(io::ErrorKind::WouldBlock)` is returned.

## tokio::try_write_vectored (function)

Tries to write several buffers to the stream, returning how many bytes
were written.

Data is written from each buffer in order, with the final buffer read
from possible being only partially consumed. This method behaves
equivalently to a single call to [`try_write()`] with concatenated
buffers.

This function is usually paired with `writable()`.

[`try_write()`]: Self::try_write()

### tokio::try_write_vectored (function) › Return

If data is successfully written, `Ok(n)` is returned, where `n` is the
number of bytes written. If the stream is not ready to write data,
`Err(io::ErrorKind::WouldBlock)` is returned.

## tokio::try_write_vectored (function)

Tries to write several buffers to the stream, returning how many bytes
were written.

Data is written from each buffer in order, with the final buffer read
from possible being only partially consumed. This method behaves
equivalently to a single call to [`try_write()`] with concatenated
buffers.

This function is usually paired with `writable()`.

[`try_write()`]: Self::try_write()

### tokio::try_write_vectored (function) › Return

If data is successfully written, `Ok(n)` is returned, where `n` is the
number of bytes written. If the stream is not ready to write data,
`Err(io::ErrorKind::WouldBlock)` is returned.

## tokio::try_write_vectored (function)

Tries to write several buffers to the stream, returning how many bytes
were written.

Data is written from each buffer in order, with the final buffer read
from possible being only partially consumed. This method behaves
equivalently to a single call to [`try_write()`] with concatenated
buffers.

This function is usually paired with `writable()`.

[`try_write()`]: UnixStream::try_write()

### tokio::try_write_vectored (function) › Return

If data is successfully written, `Ok(n)` is returned, where `n` is the
number of bytes written. If the stream is not ready to write data,
`Err(io::ErrorKind::WouldBlock)` is returned.

### tokio::try_write_vectored (function) › Examples

```no_run
use tokio::net::UnixStream;
use std::error::Error;
use std::io;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // Connect to a peer
    let dir = tempfile::tempdir().unwrap();
    let bind_path = dir.path().join("bind_path");
    let stream = UnixStream::connect(bind_path).await?;

    let bufs = [io::IoSlice::new(b"hello "), io::IoSlice::new(b"world")];

    loop {
        // Wait for the socket to be writable
        stream.writable().await?;

        // Try to write data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match stream.try_write_vectored(&bufs) {
            Ok(n) => {
                break;
            }
            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    Ok(())
}
```

## tokio::try_write_vectored (function)

Tries to write several buffers to the stream, returning how many bytes
were written.

Data is written from each buffer in order, with the final buffer read
from possibly being only partially consumed. This method behaves
equivalently to a single call to [`try_write()`] with concatenated
buffers.

This function is usually paired with `writable()`.

[`try_write()`]: TcpStream::try_write()

### tokio::try_write_vectored (function) › Return

If data is successfully written, `Ok(n)` is returned, where `n` is the
number of bytes written. If the stream is not ready to write data,
`Err(io::ErrorKind::WouldBlock)` is returned.

### tokio::try_write_vectored (function) › Examples

```no_run
use tokio::net::TcpStream;
use std::error::Error;
use std::io;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // Connect to a peer
    let stream = TcpStream::connect("127.0.0.1:8080").await?;

    let bufs = [io::IoSlice::new(b"hello "), io::IoSlice::new(b"world")];

    loop {
        // Wait for the socket to be writable
        stream.writable().await?;

        // Try to write data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match stream.try_write_vectored(&bufs) {
            Ok(n) => {
                break;
            }
            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    Ok(())
}
```

## tokio::ttl (function)

Gets the value of the `IP_TTL` option for this socket.

For more information about this option, see [`set_ttl`].

[`set_ttl`]: TcpStream::set_ttl

### tokio::ttl (function) › Examples

```no_run
use tokio::net::TcpStream;

# async fn dox() -> Result<(), Box<dyn std::error::Error>> {
let stream = TcpStream::connect("127.0.0.1:8080").await?;

println!("{:?}", stream.ttl()?);
# Ok(())
# }
```

## tokio::ttl (function)

Gets the value of the `IP_TTL` option for this socket.

For more information about this option, see [`set_ttl`].

[`set_ttl`]: method@Self::set_ttl

### tokio::ttl (function) › Examples

```no_run
use tokio::net::TcpListener;

use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
   let listener = TcpListener::bind("127.0.0.1:0").await?;

   listener.set_ttl(100).expect("could not set TTL");
   assert_eq!(listener.ttl()?, 100);

   Ok(())
}
```

## tokio::ttl (function)

Gets the value of the `IP_TTL` option for this socket.

For more information about this option, see [`set_ttl`].

[`set_ttl`]: method@Self::set_ttl

### tokio::ttl (function) › Examples

```no_run
use tokio::net::UdpSocket;
# use std::io;

# async fn dox() -> io::Result<()> {
let sock = UdpSocket::bind("127.0.0.1:8080").await?;

println!("{:?}", sock.ttl()?);
# Ok(())
# }
```

## tokio::uid (function)

Gets UID (user ID) of the process.

## tokio::uid (function)

Sets the child process's user ID. This translates to a
`setuid` call in the child process. Failure in the `setuid`
call will cause the spawn to fail.

## tokio::unchecked (function)

Sets the option to skip the check for FIFO file type.

By default, [`open_receiver`] and [`open_sender`] functions will check
if the opened file is a FIFO file. Set this option to `true` if you are
sure the file is a FIFO file.

[`open_receiver`]: OpenOptions::open_receiver
[`open_sender`]: OpenOptions::open_sender

### tokio::unchecked (function) › Examples

```no_run
use tokio::net::unix::pipe;
use nix::{unistd::mkfifo, sys::stat::Mode};
# use std::error::Error;

// Our program has exclusive access to this path.
const FIFO_NAME: &str = "path/to/a/new/fifo";

# async fn dox() -> Result<(), Box<dyn Error>> {
mkfifo(FIFO_NAME, Mode::S_IRWXU)?;
let rx = pipe::OpenOptions::new()
    .unchecked(true)
    .open_receiver(FIFO_NAME)?;
# Ok(())
# }
```

## tokio::unfilled_mut (function)

Returns a mutable reference to the unfilled part of the buffer without ensuring that it has been fully
initialized.

### tokio::unfilled_mut (function) › Safety

The caller must not de-initialize portions of the buffer that have already been initialized.
This includes any bytes in the region marked as uninitialized by `ReadBuf`.

## tokio::unhandled_panic (function)

Configure how the `LocalSet` responds to an unhandled panic on a
spawned task.

By default, an unhandled panic (i.e. a panic not caught by
[`std::panic::catch_unwind`]) has no impact on the `LocalSet`'s
execution. The panic is error value is forwarded to the task's
[`JoinHandle`] and all other spawned tasks continue running.

The `unhandled_panic` option enables configuring this behavior.

* `UnhandledPanic::Ignore` is the default behavior. Panics on
  spawned tasks have no impact on the `LocalSet`'s execution.
* `UnhandledPanic::ShutdownRuntime` will force the `LocalSet` to
  shutdown immediately when a spawned task panics even if that
  task's `JoinHandle` has not been dropped. All other spawned tasks
  will immediately terminate and further calls to
  [`LocalSet::block_on`] and [`LocalSet::run_until`] will panic.

### tokio::unhandled_panic (function) › Panics

This method panics if called after the `LocalSet` has started
running.

### tokio::unhandled_panic (function) › Unstable

This option is currently unstable and its implementation is
incomplete. The API may change or be removed in the future. See
tokio-rs/tokio#4516 for more details.

### tokio::unhandled_panic (function) › Examples

The following demonstrates a `LocalSet` configured to shutdown on
panic. The first spawned task panics and results in the `LocalSet`
shutting down. The second spawned task never has a chance to
execute. The call to `run_until` will panic due to the runtime being
forcibly shutdown.

```should_panic
use tokio::runtime::UnhandledPanic;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
tokio::task::LocalSet::new()
    .unhandled_panic(UnhandledPanic::ShutdownRuntime)
    .run_until(async {
        tokio::task::spawn_local(async { panic!("boom"); });
        tokio::task::spawn_local(async {
            // This task never completes
        });

        // Do some work, but `run_until` will panic before it completes
# loop { tokio::task::yield_now().await; }
    })
    .await;
# }
```

[`JoinHandle`]: struct@crate::task::JoinHandle

## tokio::unhandled_panic (function)

Configure how the runtime responds to an unhandled panic on a
spawned task.

By default, an unhandled panic (i.e. a panic not caught by
[`std::panic::catch_unwind`]) has no impact on the runtime's
execution. The panic's error value is forwarded to the task's
[`JoinHandle`] and all other spawned tasks continue running.

The `unhandled_panic` option enables configuring this behavior.

* `UnhandledPanic::Ignore` is the default behavior. Panics on
  spawned tasks have no impact on the runtime's execution.
* `UnhandledPanic::ShutdownRuntime` will force the runtime to
  shutdown immediately when a spawned task panics even if that
  task's `JoinHandle` has not been dropped. All other spawned tasks
  will immediately terminate and further calls to
  [`Runtime::block_on`] will panic.

### tokio::unhandled_panic (function) › Panics
This method panics if called with [`UnhandledPanic::ShutdownRuntime`]
on a runtime other than the current thread runtime.

### tokio::unhandled_panic (function) › Unstable

This option is currently unstable and its implementation is
incomplete. The API may change or be removed in the future. See
issue [tokio-rs/tokio#4516] for more details.

### tokio::unhandled_panic (function) › Examples

The following demonstrates a runtime configured to shutdown on
panic. The first spawned task panics and results in the runtime
shutting down. The second spawned task never has a chance to
execute. The call to `block_on` will panic due to the runtime being
forcibly shutdown.

```should_panic
use tokio::runtime::{self, UnhandledPanic};

# pub fn main() {
let rt = runtime::Builder::new_current_thread()
    .unhandled_panic(UnhandledPanic::ShutdownRuntime)
    .build()
    .unwrap();

rt.spawn(async { panic!("boom"); });
rt.spawn(async {
    // This task never completes.
});

rt.block_on(async {
    // Do some work
# loop { tokio::task::yield_now().await; }
})
# }
```

[`JoinHandle`]: struct@crate::task::JoinHandle
[tokio-rs/tokio#4516]: https://github.com/tokio-rs/tokio/issues/4516

## tokio::uninit (function)

Creates a new `ReadBuf` from a buffer that may be uninitialized.

The internal cursor will mark the entire buffer as uninitialized. If
the buffer is known to be partially initialized, then use `assume_init`
to move the internal cursor.

## tokio::unsplit (function)

Reunites with a previously split `WriteHalf`.

### tokio::unsplit (function) › Panics

If this `ReadHalf` and the given `WriteHalf` do not originate from the
same `split` operation this method will panic.
This can be checked ahead of time by calling [`is_pair_of()`](Self::is_pair_of).

## tokio::upgrade (function)

Tries to convert a `WeakSender` into a [`Sender`].

This will return `Some` if there are other `Sender` instances alive and
the channel wasn't previously dropped, otherwise `None` is returned.

## tokio::upgrade (function)

Tries to convert a `WeakSender` into a [`Sender`]. This will return `Some`
if there are other `Sender` instances alive and the channel wasn't
previously dropped, otherwise `None` is returned.

## tokio::upgrade (function)

Tries to convert a `WeakUnboundedSender` into an [`UnboundedSender`].
This will return `Some` if there are other `Sender` instances alive and
the channel wasn't previously dropped, otherwise `None` is returned.

## tokio::user_defined1 (function)

Represents the `SIGUSR1` signal.

On Unix systems this is a user defined signal.
By default, the process is terminated by this signal.

## tokio::user_defined2 (function)

Represents the `SIGUSR2` signal.

On Unix systems this is a user defined signal.
By default, the process is terminated by this signal.

## tokio::util::rand::RngSeed (struct)

A seed for random number generation.

In order to make certain functions within a runtime deterministic, a seed
can be specified at the time of creation.

## tokio::wait (function)

Does not resolve until all tasks have rendezvoused here.

Barriers are re-usable after all tasks have rendezvoused once, and can
be used continuously.

A single (arbitrary) future will receive a [`BarrierWaitResult`] that returns `true` from
[`BarrierWaitResult::is_leader`] when returning from this function, and all other tasks
will receive a result that will return `false` from `is_leader`.

### tokio::wait (function) › Cancel safety

This method is not cancel safe.

## tokio::wait (function)

Waits for the child to exit completely, returning the status that it
exited with. This function will continue to have the same return value
after it has been called at least once.

The stdin handle to the child process, if any, will be closed
before waiting. This helps avoid deadlock: it ensures that the
child does not block waiting for input from the parent, while
the parent waits for the child to exit.

If the caller wishes to explicitly control when the child's stdin
handle is closed, they may `.take()` it before calling `.wait()`:

### tokio::wait (function) › Cancel safety

This function is cancel safe.

```
# #[cfg(not(unix))]fn main(){}
# #[cfg(unix)]
use tokio::io::AsyncWriteExt;
# #[cfg(unix)]
use tokio::process::Command;
# #[cfg(unix)]
use std::process::Stdio;

# #[cfg(unix)]
#[tokio::main]
async fn main() {
#   if cfg!(miri) { return; } // No `pidfd_spawnp` in miri.
    let mut child = Command::new("cat")
        .stdin(Stdio::piped())
        .spawn()
        .unwrap();

    let mut stdin = child.stdin.take().unwrap();
    tokio::spawn(async move {
        // do something with stdin here...
        stdin.write_all(b"hello world\n").await.unwrap();

        // then drop when finished
        drop(stdin);
    });

    // wait for the process to complete
    let _ = child.wait().await;
}
```

## tokio::wait (function)

Waits until the value is set.

If the `SetOnce` is already initialized, it will return the value
immediately.

### tokio::wait (function) › Cancel safety

This method is cancel safe.

## tokio::wait_for (function)

Waits for a value that satisfies the provided condition.

This method will call the provided closure whenever something is sent on
the channel. Once the closure returns `true`, this method will return a
reference to the value that was passed to the closure.

Before `wait_for` starts waiting for changes, it will call the closure
on the current value. If the closure returns `true` when given the
current value, then `wait_for` will immediately return a reference to
the current value. This is the case even if the current value is already
considered seen.

The watch channel only keeps track of the most recent value, so if
several messages are sent faster than `wait_for` is able to call the
closure, then it may skip some updates. Whenever the closure is called,
it will be called with the most recent value.

When this function returns, the value that was passed to the closure
when it returned `true` will be considered seen.

If the channel is closed, then `wait_for` will return a [`RecvError`].
Once this happens, no more messages can ever be sent on the channel.
When an error is returned, it is guaranteed that the closure has been
called on the last value, and that it returned `false` for that value.
(If the closure returned `true`, then the last value would have been
returned instead of the error.)

Like the [`borrow`] method, the returned borrow holds a read lock on the
inner value. This means that long-lived borrows could cause the producer
half to block. It is recommended to keep the borrow as short-lived as
possible. See the documentation of `borrow` for more information on
this.

[`borrow`]: Receiver::borrow
[`RecvError`]: error::RecvError

### tokio::wait_for (function) › Cancel safety

This method is cancel safe. If you use it as a branch in
[`tokio::select!`](crate::select) and another branch
completes first, then it is guaranteed that the last seen value `val`
(if any) satisfies `f(val) == false`.

### tokio::wait_for (function) › Panics

If and only if the closure `f` panics. In that case, no resource owned
or shared by this [`Receiver`] will be poisoned.

### tokio::wait_for (function) › Examples

```
use tokio::sync::watch;
use tokio::time::{sleep, Duration};

#[tokio::main(flavor = "current_thread", start_paused = true)]
async fn main() {
    let (tx, mut rx) = watch::channel("hello");

    tokio::spawn(async move {
        sleep(Duration::from_secs(1)).await;
        tx.send("goodbye").unwrap();
    });

    assert!(rx.wait_for(|val| *val == "goodbye").await.is_ok());
    assert_eq!(*rx.borrow(), "goodbye");
}
```

## tokio::wait_with_output (function)

Returns a future that will resolve to an `Output`, containing the exit
status, stdout, and stderr of the child process.

The returned future will simultaneously waits for the child to exit and
collect all remaining output on the stdout/stderr handles, returning an
`Output` instance.

The stdin handle to the child process, if any, will be closed before
waiting. This helps avoid deadlock: it ensures that the child does not
block waiting for input from the parent, while the parent waits for the
child to exit.

By default, stdin, stdout and stderr are inherited from the parent. In
order to capture the output into this `Output` it is necessary to create
new pipes between parent and child. Use `stdout(Stdio::piped())` or
`stderr(Stdio::piped())`, respectively, when creating a `Command`.

## tokio::weak_count (function)

Returns the number of [`WeakSender`] handles.

## tokio::weak_count (function)

Returns the number of [`WeakSender`] handles.

## tokio::weak_count (function)

Returns the number of [`WeakSender`] handles.

## tokio::weak_count (function)

Returns the number of [`WeakSender`] handles.

## tokio::weak_count (function)

Returns the number of [`WeakUnboundedSender`] handles.

## tokio::weak_count (function)

Returns the number of [`WeakUnboundedSender`] handles.

## tokio::window_change (function)

Represents the `SIGWINCH` signal.

On Unix systems this signal is sent when the terminal window is resized.
By default, this signal is ignored.

## tokio::with (function)

Accesses the current task-local and runs the provided closure.

### tokio::with (function) › Panics

This function will panic if the task local doesn't have a value set.

## tokio::with_capacity (function)

Creates a `BufStream` with the specified [`BufReader`] capacity and [`BufWriter`]
capacity.

See the documentation for those types and [`BufStream`] for details.

## tokio::with_capacity (function)

Creates a new `BufReader` with the specified buffer capacity.

## tokio::with_capacity (function)

Creates a new `BufWriter` with the specified buffer capacity.

## tokio::with_interest (function)

Creates an [`AsyncFd`] backed by (and taking ownership of) an object
implementing [`AsRawFd`], with a specific [`Interest`]. The backing
file descriptor is cached at the time of creation.

### tokio::with_interest (function) › Panics

This function panics if there is no current reactor set, or if the `rt`
feature flag is not enabled.

## tokio::with_max_readers (function)

Creates a new instance of an `RwLock<T>` which is unlocked
and allows a maximum of `max_reads` concurrent readers.

### tokio::with_max_readers (function) › Examples

```
use tokio::sync::RwLock;

let lock = RwLock::with_max_readers(5, 1024);
```

### tokio::with_max_readers (function) › Panics

Panics if `max_reads` is `0` or is bigger than `u32::MAX >> 3`.

## tokio::worker_local_queue_depth (function)

Returns the number of tasks currently scheduled in the given worker's
local queue.

Tasks that are spawned or notified from within a runtime thread are
scheduled using that worker's local queue. This metric returns the
**current** number of tasks pending in the worker's local queue. As
such, the returned value may increase or decrease as new tasks are
scheduled and processed.

### tokio::worker_local_queue_depth (function) › Arguments

`worker` is the index of the worker being queried. The given value must
be between 0 and `num_workers()`. The index uniquely identifies a single
worker and will continue to identify the worker throughout the lifetime
of the runtime instance.

### tokio::worker_local_queue_depth (function) › Panics

The method panics when `worker` represents an invalid worker, i.e. is
greater than or equal to `num_workers()`.

### tokio::worker_local_queue_depth (function) › Examples

```
use tokio::runtime::Handle;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let metrics = Handle::current().metrics();

let n = metrics.worker_local_queue_depth(0);
println!("{} tasks currently pending in worker 0's local queue", n);
# }
```

## tokio::worker_local_schedule_count (function)

Returns the number of tasks scheduled from **within** the runtime on the
given worker's local queue.

The local schedule count starts at zero when the runtime is created and
increases by one each time a task is woken from **inside** of the
runtime on the given worker. This usually means that a task is spawned
or notified from within a runtime thread and will be queued on the
worker-local queue.

The counter is monotonically increasing. It is never decremented or
reset to zero.

### tokio::worker_local_schedule_count (function) › Arguments

`worker` is the index of the worker being queried. The given value must
be between 0 and `num_workers()`. The index uniquely identifies a single
worker and will continue to identify the worker throughout the lifetime
of the runtime instance.

### tokio::worker_local_schedule_count (function) › Panics

The method panics when `worker` represents an invalid worker, i.e. is
greater than or equal to `num_workers()`.

### tokio::worker_local_schedule_count (function) › Examples

```
use tokio::runtime::Handle;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let metrics = Handle::current().metrics();

let n = metrics.worker_local_schedule_count(0);
println!("{} tasks were scheduled on the worker's local queue", n);
# }
```

## tokio::worker_mean_poll_time (function)

Returns the mean duration of task polls, in nanoseconds.

This is an exponentially weighted moving average. Currently, this metric
is only provided by the multi-threaded runtime.

### tokio::worker_mean_poll_time (function) › Arguments

`worker` is the index of the worker being queried. The given value must
be between 0 and `num_workers()`. The index uniquely identifies a single
worker and will continue to identify the worker throughout the lifetime
of the runtime instance.

### tokio::worker_mean_poll_time (function) › Panics

The method panics when `worker` represents an invalid worker, i.e. is
greater than or equal to `num_workers()`.

### tokio::worker_mean_poll_time (function) › Examples

```
use tokio::runtime::Handle;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let metrics = Handle::current().metrics();

let n = metrics.worker_mean_poll_time(0);
println!("worker 0 has a mean poll time of {:?}", n);
# }
```

## tokio::worker_noop_count (function)

Returns the number of times the given worker thread unparked but
performed no work before parking again.

The worker no-op count starts at zero when the runtime is created and
increases by one each time the worker unparks the thread but finds no
new work and goes back to sleep. This indicates a false-positive wake up.

The counter is monotonically increasing. It is never decremented or
reset to zero.

### tokio::worker_noop_count (function) › Arguments

`worker` is the index of the worker being queried. The given value must
be between 0 and `num_workers()`. The index uniquely identifies a single
worker and will continue to identify the worker throughout the lifetime
of the runtime instance.

### tokio::worker_noop_count (function) › Panics

The method panics when `worker` represents an invalid worker, i.e. is
greater than or equal to `num_workers()`.

### tokio::worker_noop_count (function) › Examples

```
use tokio::runtime::Handle;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let metrics = Handle::current().metrics();

let n = metrics.worker_noop_count(0);
println!("worker 0 had {} no-op unparks", n);
# }
```

## tokio::worker_overflow_count (function)

Returns the number of times the given worker thread saturated its local
queue.

This metric only applies to the **multi-threaded** scheduler.

The worker overflow count starts at zero when the runtime is created and
increases by one each time the worker attempts to schedule a task
locally, but its local queue is full. When this happens, half of the
local queue is moved to the injection queue.

The counter is monotonically increasing. It is never decremented or
reset to zero.

### tokio::worker_overflow_count (function) › Arguments

`worker` is the index of the worker being queried. The given value must
be between 0 and `num_workers()`. The index uniquely identifies a single
worker and will continue to identify the worker throughout the lifetime
of the runtime instance.

### tokio::worker_overflow_count (function) › Panics

The method panics when `worker` represents an invalid worker, i.e. is
greater than or equal to `num_workers()`.

### tokio::worker_overflow_count (function) › Examples

```
use tokio::runtime::Handle;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let metrics = Handle::current().metrics();

let n = metrics.worker_overflow_count(0);
println!("worker 0 has overflowed its queue {} times", n);
# }
```

## tokio::worker_park_count (function)

Returns the total number of times the given worker thread has parked.

The worker park count starts at zero when the runtime is created and
increases by one each time the worker parks the thread waiting for new
inbound events to process. This usually means the worker has processed
all pending work and is currently idle.

The counter is monotonically increasing. It is never decremented or
reset to zero.

### tokio::worker_park_count (function) › Arguments

`worker` is the index of the worker being queried. The given value must
be between 0 and `num_workers()`. The index uniquely identifies a single
worker and will continue to identify the worker throughout the lifetime
of the runtime instance.

### tokio::worker_park_count (function) › Panics

The method panics when `worker` represents an invalid worker, i.e. is
greater than or equal to `num_workers()`.

### tokio::worker_park_count (function) › Examples

```
use tokio::runtime::Handle;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let metrics = Handle::current().metrics();

let n = metrics.worker_park_count(0);
println!("worker 0 parked {} times", n);
# }
```

## tokio::worker_park_unpark_count (function)

Returns the total number of times the given worker thread has parked
and unparked.

The worker park/unpark count starts at zero when the runtime is created
and increases by one each time the worker parks the thread waiting for
new inbound events to process. This usually means the worker has processed
all pending work and is currently idle. When new work becomes available,
the worker is unparked and the park/unpark count is again increased by one.

An odd count means that the worker is currently parked.
An even count means that the worker is currently active.

The counter is monotonically increasing. It is never decremented or
reset to zero.

### tokio::worker_park_unpark_count (function) › Arguments

`worker` is the index of the worker being queried. The given value must
be between 0 and `num_workers()`. The index uniquely identifies a single
worker and will continue to identify the worker throughout the lifetime
of the runtime instance.

### tokio::worker_park_unpark_count (function) › Panics

The method panics when `worker` represents an invalid worker, i.e. is
greater than or equal to `num_workers()`.

### tokio::worker_park_unpark_count (function) › Examples

```
use tokio::runtime::Handle;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let metrics = Handle::current().metrics();
let n = metrics.worker_park_unpark_count(0);

println!("worker 0 parked and unparked {} times", n);

if n % 2 == 0 {
    println!("worker 0 is active");
} else {
    println!("worker 0 is parked");
}
# }
```

## tokio::worker_poll_count (function)

Returns the number of tasks the given worker thread has polled.

The worker poll count starts at zero when the runtime is created and
increases by one each time the worker polls a scheduled task.

The counter is monotonically increasing. It is never decremented or
reset to zero.

### tokio::worker_poll_count (function) › Arguments

`worker` is the index of the worker being queried. The given value must
be between 0 and `num_workers()`. The index uniquely identifies a single
worker and will continue to identify the worker throughout the lifetime
of the runtime instance.

### tokio::worker_poll_count (function) › Panics

The method panics when `worker` represents an invalid worker, i.e. is
greater than or equal to `num_workers()`.

### tokio::worker_poll_count (function) › Examples

```
use tokio::runtime::Handle;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let metrics = Handle::current().metrics();

let n = metrics.worker_poll_count(0);
println!("worker 0 has polled {} tasks", n);
# }
```

## tokio::worker_steal_count (function)

Returns the number of tasks the given worker thread stole from
another worker thread.

This metric only applies to the **multi-threaded** runtime and will
always return `0` when using the current thread runtime.

The worker steal count starts at zero when the runtime is created and
increases by `N` each time the worker has processed its scheduled queue
and successfully steals `N` more pending tasks from another worker.

The counter is monotonically increasing. It is never decremented or
reset to zero.

### tokio::worker_steal_count (function) › Arguments

`worker` is the index of the worker being queried. The given value must
be between 0 and `num_workers()`. The index uniquely identifies a single
worker and will continue to identify the worker throughout the lifetime
of the runtime instance.

### tokio::worker_steal_count (function) › Panics

The method panics when `worker` represents an invalid worker, i.e. is
greater than or equal to `num_workers()`.

### tokio::worker_steal_count (function) › Examples

```
use tokio::runtime::Handle;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let metrics = Handle::current().metrics();

let n = metrics.worker_steal_count(0);
println!("worker 0 has stolen {} tasks", n);
# }
```

## tokio::worker_steal_operations (function)

Returns the number of times the given worker thread stole tasks from
another worker thread.

This metric only applies to the **multi-threaded** runtime and will
always return `0` when using the current thread runtime.

The worker steal count starts at zero when the runtime is created and
increases by one each time the worker has processed its scheduled queue
and successfully steals more pending tasks from another worker.

The counter is monotonically increasing. It is never decremented or
reset to zero.

### tokio::worker_steal_operations (function) › Arguments

`worker` is the index of the worker being queried. The given value must
be between 0 and `num_workers()`. The index uniquely identifies a single
worker and will continue to identify the worker throughout the lifetime
of the runtime instance.

### tokio::worker_steal_operations (function) › Panics

The method panics when `worker` represents an invalid worker, i.e. is
greater than or equal to `num_workers()`.

### tokio::worker_steal_operations (function) › Examples

```
use tokio::runtime::Handle;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let metrics = Handle::current().metrics();

let n = metrics.worker_steal_operations(0);
println!("worker 0 has stolen tasks {} times", n);
# }
```

## tokio::worker_thread_id (function)

Returns the thread id of the given worker thread.

The returned value is `None` if the worker thread has not yet finished
starting up.

If additional information about the thread, such as its native id, are
required, those can be collected in [`on_thread_start`] and correlated
using the thread id.

[`on_thread_start`]: crate::runtime::Builder::on_thread_start

### tokio::worker_thread_id (function) › Arguments

`worker` is the index of the worker being queried. The given value must
be between 0 and `num_workers()`. The index uniquely identifies a single
worker and will continue to identify the worker throughout the lifetime
of the runtime instance.

### tokio::worker_thread_id (function) › Panics

The method panics when `worker` represents an invalid worker, i.e. is
greater than or equal to `num_workers()`.

### tokio::worker_thread_id (function) › Examples

```
use tokio::runtime::Handle;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let metrics = Handle::current().metrics();

let id = metrics.worker_thread_id(0);
println!("worker 0 has id {:?}", id);
# }
```

## tokio::worker_threads (function)

Sets the number of worker threads the `Runtime` will use.

This can be any number above 0 though it is advised to keep this value
on the smaller side.

This will override the value read from environment variable `TOKIO_WORKER_THREADS`.

### tokio::worker_threads (function) › Default

The default value is the number of cores available to the system.

When using the `current_thread` runtime this method has no effect.

### tokio::worker_threads (function) › Examples

### tokio::worker_threads (function) › Multi threaded runtime with 4 threads

```
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime;

// This will spawn a work-stealing runtime with 4 worker threads.
let rt = runtime::Builder::new_multi_thread()
    .worker_threads(4)
    .build()
    .unwrap();

rt.spawn(async move {});
# }
```

### tokio::worker_threads (function) › Current thread runtime (will only run on the current thread via `Runtime::block_on`)

```
use tokio::runtime;

// Create a runtime that _must_ be driven from a call
// to `Runtime::block_on`.
let rt = runtime::Builder::new_current_thread()
    .build()
    .unwrap();

// This will run the runtime and future on the current thread
rt.block_on(async move {});
```

### tokio::worker_threads (function) › Panics

This will panic if `val` is not larger than `0`.

## tokio::worker_total_busy_duration (function)

Returns the amount of time the given worker thread has been busy.

The worker busy duration starts at zero when the runtime is created and
increases whenever the worker is spending time processing work. Using
this value can indicate the load of the given worker. If a lot of time
is spent busy, then the worker is under load and will check for inbound
events less often.

The timer is monotonically increasing. It is never decremented or reset
to zero.

### tokio::worker_total_busy_duration (function) › Arguments

`worker` is the index of the worker being queried. The given value must
be between 0 and `num_workers()`. The index uniquely identifies a single
worker and will continue to identify the worker throughout the lifetime
of the runtime instance.

### tokio::worker_total_busy_duration (function) › Panics

The method panics when `worker` represents an invalid worker, i.e. is
greater than or equal to `num_workers()`.

### tokio::worker_total_busy_duration (function) › Examples

```
use tokio::runtime::Handle;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let metrics = Handle::current().metrics();

let n = metrics.worker_total_busy_duration(0);
println!("worker 0 was busy for a total of {:?}", n);
# }
```

## tokio::writable (function)

Waits for the file descriptor to become writable, returning a
[`AsyncFdReadyGuard`] that must be dropped to resume write-readiness
polling.

This method takes `&self`, so it is possible to call this method
concurrently with other methods on this struct. This method only
provides shared access to the inner IO resource when handling the
[`AsyncFdReadyGuard`].

### tokio::writable (function) › Cancel safety

This method is cancel safe. Once a readiness event occurs, the method
will continue to return immediately until the readiness event is
consumed by an attempt to read or write that fails with `WouldBlock` or
`Poll::Pending`.

## tokio::writable (function)

Waits for the pipe to become writable.

This function is equivalent to `ready(Interest::WRITABLE)` and is usually
paired with [`try_write()`].

[`try_write()`]: Self::try_write

### tokio::writable (function) › Examples

```no_run
use tokio::net::unix::pipe;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    // Open a writing end of a fifo
    let tx = pipe::OpenOptions::new().open_sender("path/to/a/fifo")?;

    loop {
        // Wait for the pipe to be writable
        tx.writable().await?;

        // Try to write data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match tx.try_write(b"hello world") {
            Ok(n) => {
                break;
            }
            Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    Ok(())
}
```

## tokio::writable (function)

Waits for the pipe to become writable.

This function is equivalent to `ready(Interest::WRITABLE)` and is usually
paired with `try_write()`.

### tokio::writable (function) › Examples

```no_run
use tokio::net::windows::named_pipe;
use std::error::Error;
use std::io;

const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-client-writable";

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let client = named_pipe::ClientOptions::new().open(PIPE_NAME)?;

    loop {
        // Wait for the pipe to be writable
        client.writable().await?;

        // Try to write data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match client.try_write(b"hello world") {
            Ok(n) => {
                break;
            }
            Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    Ok(())
}
```

## tokio::writable (function)

Waits for the pipe to become writable.

This function is equivalent to `ready(Interest::WRITABLE)` and is usually
paired with `try_write()`.

### tokio::writable (function) › Examples

```no_run
use tokio::net::windows::named_pipe;
use std::error::Error;
use std::io;

const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-server-writable";

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let server = named_pipe::ServerOptions::new()
        .create(PIPE_NAME)?;

    loop {
        // Wait for the pipe to be writable
        server.writable().await?;

        // Try to write data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match server.try_write(b"hello world") {
            Ok(n) => {
                break;
            }
            Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    Ok(())
}
```

## tokio::writable (function)

Waits for the socket to become writable.

This function is equivalent to `ready(Interest::WRITABLE)` and is
usually paired with `try_send()` or `try_send_to()`.

The function may complete without the socket being writable. This is a
false-positive and attempting a `try_send()` will return with
`io::ErrorKind::WouldBlock`.

### tokio::writable (function) › Cancel safety

This method is cancel safe. Once a readiness event occurs, the method
will continue to return immediately until the readiness event is
consumed by an attempt to write that fails with `WouldBlock` or
`Poll::Pending`.

### tokio::writable (function) › Examples

```no_run
use tokio::net::UdpSocket;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    // Bind socket
    let socket = UdpSocket::bind("127.0.0.1:8080").await?;
    socket.connect("127.0.0.1:8081").await?;

    loop {
        // Wait for the socket to be writable
        socket.writable().await?;

        // Try to send data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match socket.try_send(b"hello world") {
            Ok(n) => {
                break;
            }
            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e);
            }
        }
    }

    Ok(())
}
```

## tokio::writable (function)

Waits for the socket to become writable.

This function is equivalent to `ready(Interest::WRITABLE)` and is usually
paired with `try_write()`.

### tokio::writable (function) › Cancel safety

This method is cancel safe. Once a readiness event occurs, the method
will continue to return immediately until the readiness event is
consumed by an attempt to write that fails with `WouldBlock` or
`Poll::Pending`.

## tokio::writable (function)

Waits for the socket to become writable.

This function is equivalent to `ready(Interest::WRITABLE)` and is usually
paired with `try_write()`.

### tokio::writable (function) › Cancel safety

This method is cancel safe. Once a readiness event occurs, the method
will continue to return immediately until the readiness event is
consumed by an attempt to write that fails with `WouldBlock` or
`Poll::Pending`.

## tokio::writable (function)

Waits for the socket to become writable.

This function is equivalent to `ready(Interest::WRITABLE)` and is usually
paired with `try_write()`.

### tokio::writable (function) › Cancel safety

This method is cancel safe. Once a readiness event occurs, the method
will continue to return immediately until the readiness event is
consumed by an attempt to write that fails with `WouldBlock` or
`Poll::Pending`.

## tokio::writable (function)

Waits for the socket to become writable.

This function is equivalent to `ready(Interest::WRITABLE)` and is usually
paired with `try_write()`.

### tokio::writable (function) › Cancel safety

This method is cancel safe. Once a readiness event occurs, the method
will continue to return immediately until the readiness event is
consumed by an attempt to write that fails with `WouldBlock` or
`Poll::Pending`.

## tokio::writable (function)

Waits for the socket to become writable.

This function is equivalent to `ready(Interest::WRITABLE)` and is usually
paired with `try_write()`.

### tokio::writable (function) › Cancel safety

This method is cancel safe. Once a readiness event occurs, the method
will continue to return immediately until the readiness event is
consumed by an attempt to write that fails with `WouldBlock` or
`Poll::Pending`.

### tokio::writable (function) › Examples

```no_run
use tokio::net::TcpStream;
use std::error::Error;
use std::io;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // Connect to a peer
    let stream = TcpStream::connect("127.0.0.1:8080").await?;

    loop {
        // Wait for the socket to be writable
        stream.writable().await?;

        // Try to write data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match stream.try_write(b"hello world") {
            Ok(n) => {
                break;
            }
            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    Ok(())
}
```

## tokio::writable (function)

Waits for the socket to become writable.

This function is equivalent to `ready(Interest::WRITABLE)` and is usually
paired with `try_write()`.

### tokio::writable (function) › Cancel safety

This method is cancel safe. Once a readiness event occurs, the method
will continue to return immediately until the readiness event is
consumed by an attempt to write that fails with `WouldBlock` or
`Poll::Pending`.

### tokio::writable (function) › Examples

```no_run
use tokio::net::UnixStream;
use std::error::Error;
use std::io;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // Connect to a peer
    let dir = tempfile::tempdir().unwrap();
    let bind_path = dir.path().join("bind_path");
    let stream = UnixStream::connect(bind_path).await?;

    loop {
        // Wait for the socket to be writable
        stream.writable().await?;

        // Try to write data, this may still fail with `WouldBlock`
        // if the readiness event is a false positive.
        match stream.try_write(b"hello world") {
            Ok(n) => {
                break;
            }
            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                continue;
            }
            Err(e) => {
                return Err(e.into());
            }
        }
    }

    Ok(())
}
```

## tokio::writable_mut (function)

Waits for the file descriptor to become writable, returning a
[`AsyncFdReadyMutGuard`] that must be dropped to resume write-readiness
polling.

This method takes `&mut self`, so it is possible to access the inner IO
resource mutably when handling the [`AsyncFdReadyMutGuard`].

### tokio::writable_mut (function) › Cancel safety

This method is cancel safe. Once a readiness event occurs, the method
will continue to return immediately until the readiness event is
consumed by an attempt to read or write that fails with `WouldBlock` or
`Poll::Pending`.

## tokio::write (function)

If the created pipe supports writing data. This is enabled by default.

This corresponds to setting [`GENERIC_WRITE`] in the call to [`CreateFile`].

[`GENERIC_WRITE`]: https://docs.microsoft.com/en-us/windows/win32/secauthz/generic-access-rights
[`CreateFile`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew

## tokio::write (function)

Locks this `RwLock` with exclusive write access, causing the current
task to yield until the lock has been acquired.

The calling task will yield while other writers or readers currently
have access to the lock.

Returns an RAII guard which will drop the write access of this `RwLock`
when dropped.

### tokio::write (function) › Cancel safety

This method uses a queue to fairly distribute locks in the order they
were requested. Cancelling a call to `write` makes you lose your place
in the queue.

### tokio::write (function) › Examples

```
use tokio::sync::RwLock;

# #[tokio::main(flavor = "current_thread")]
# async fn main() {
let lock = RwLock::new(1);

let mut n = lock.write().await;
*n = 2;
# }
```

## tokio::write (function)

Sets the option for write access.

This option, when true, will indicate that the file should be
`write`-able if opened.

This is an async version of [`std::fs::OpenOptions::write`][std]

[std]: std::fs::OpenOptions::write

### tokio::write (function) › Examples

```no_run
use tokio::fs::OpenOptions;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let file = OpenOptions::new()
        .write(true)
        .open("foo.txt")
        .await?;

    Ok(())
}
```

## tokio::write (function)

Writes a buffer into this writer, returning how many bytes were
written.

Equivalent to:

```ignore
async fn write(&mut self, buf: &[u8]) -> io::Result<usize>;
```

This function will attempt to write the entire contents of `buf`, but
the entire write may not succeed, or the write may also generate an
error. A call to `write` represents *at most one* attempt to write to
any wrapped object.

### tokio::write (function) › Return

If the return value is `Ok(n)` then it must be guaranteed that `n <=
buf.len()`. A return value of `0` typically means that the
underlying object is no longer able to accept bytes and will likely
not be able to in the future as well, or that the buffer provided is
empty.

### tokio::write (function) › Errors

Each call to `write` may generate an I/O error indicating that the
operation could not be completed. If an error is returned then no bytes
in the buffer were written to this writer.

It is **not** considered an error if the entire buffer could not be
written to this writer.

### tokio::write (function) › Cancel safety

This method is cancel safe. If it is used as a branch in
[`tokio::select!`](crate::select) and another branch completes
first, then it is guaranteed that no data was
written to this `AsyncWrite`.

### tokio::write (function) › Examples

```no_run
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::io::{self, AsyncWriteExt};
use tokio::fs::File;

#[tokio::main]
async fn main() -> io::Result<()> {
    let mut file = File::create("foo.txt").await?;

    // Writes some prefix of the byte string, not necessarily all of it.
    file.write(b"some bytes").await?;
    file.flush().await?;
    Ok(())
}
# }
```

## tokio::write_all (function)

Attempts to write an entire buffer into this writer.

Equivalent to:

```ignore
async fn write_all(&mut self, buf: &[u8]) -> io::Result<()>;
```

This method will continuously call [`write`] until there is no more data
to be written. This method will not return until the entire buffer
has been successfully written or such an error occurs. The first
error generated from this method will be returned.

### tokio::write_all (function) › Cancel safety

This method is not cancel safe. If it is used as a branch in
[`tokio::select!`](crate::select) and another branch completes
first, then the provided buffer may have been
partially written, but future calls to `write_all` will start over
from the beginning of the buffer.

### tokio::write_all (function) › Errors

This function will return the first error that [`write`] returns.

### tokio::write_all (function) › Examples

```no_run
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::io::{self, AsyncWriteExt};
use tokio::fs::File;

#[tokio::main]
async fn main() -> io::Result<()> {
    let mut file = File::create("foo.txt").await?;

    file.write_all(b"some bytes").await?;
    file.flush().await?;
    Ok(())
}
# }
```

[`write`]: AsyncWriteExt::write

## tokio::write_all_buf (function)

Attempts to write an entire buffer into this writer.

Equivalent to:

```ignore
async fn write_all_buf(&mut self, buf: impl Buf) -> Result<(), io::Error> {
    while buf.has_remaining() {
        self.write_buf(&mut buf).await?;
    }
    Ok(())
}
```

This method will continuously call [`write`] until
[`buf.has_remaining()`](bytes::Buf::has_remaining) returns false. This method will not
return until the entire buffer has been successfully written or an error occurs. The
first error generated will be returned.

The buffer is advanced after each chunk is successfully written. After failure,
`src.chunk()` will return the chunk that failed to write.

### tokio::write_all_buf (function) › Cancel safety

If `write_all_buf` is used as a branch in
[`tokio::select!`](crate::select) and another branch
completes first, then the data in the provided buffer may have been
partially written. However, it is guaranteed that the provided
buffer has been [advanced] by the amount of bytes that have been
partially written.

### tokio::write_all_buf (function) › Examples

[`File`] implements [`AsyncWrite`] and [`Cursor`]`<&[u8]>` implements [`Buf`]:

[`File`]: crate::fs::File
[`Buf`]: bytes::Buf
[`Cursor`]: std::io::Cursor
[advanced]: bytes::Buf::advance

```no_run
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::io::{self, AsyncWriteExt};
use tokio::fs::File;

use std::io::Cursor;

#[tokio::main]
async fn main() -> io::Result<()> {
    let mut file = File::create("foo.txt").await?;
    let mut buffer = Cursor::new(b"data to write");

    file.write_all_buf(&mut buffer).await?;
    file.flush().await?;
    Ok(())
}
# }
```

[`write`]: AsyncWriteExt::write

## tokio::write_buf (function)

Writes a buffer into this writer, advancing the buffer's internal
cursor.

Equivalent to:

```ignore
async fn write_buf<B: Buf>(&mut self, buf: &mut B) -> io::Result<usize>;
```

This function will attempt to write the entire contents of `buf`, but
the entire write may not succeed, or the write may also generate an
error. After the operation completes, the buffer's
internal cursor is advanced by the number of bytes written. A
subsequent call to `write_buf` using the **same** `buf` value will
resume from the point that the first call to `write_buf` completed.
A call to `write_buf` represents *at most one* attempt to write to any
wrapped object.

### tokio::write_buf (function) › Return

If the return value is `Ok(n)` then it must be guaranteed that `n <=
buf.len()`. A return value of `0` typically means that the
underlying object is no longer able to accept bytes and will likely
not be able to in the future as well, or that the buffer provided is
empty.

### tokio::write_buf (function) › Errors

Each call to `write` may generate an I/O error indicating that the
operation could not be completed. If an error is returned then no bytes
in the buffer were written to this writer.

It is **not** considered an error if the entire buffer could not be
written to this writer.

### tokio::write_buf (function) › Cancel safety

This method is cancel safe. If it is used as a branch in
[`tokio::select!`](crate::select) and another branch completes
first, then it is guaranteed that no data was
written to this `AsyncWrite`.

### tokio::write_buf (function) › Examples

[`File`] implements [`AsyncWrite`] and [`Cursor`]`<&[u8]>` implements [`Buf`]:

[`File`]: crate::fs::File
[`Buf`]: bytes::Buf
[`Cursor`]: std::io::Cursor

```no_run
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::io::{self, AsyncWriteExt};
use tokio::fs::File;

use bytes::Buf;
use std::io::Cursor;

#[tokio::main]
async fn main() -> io::Result<()> {
    let mut file = File::create("foo.txt").await?;
    let mut buffer = Cursor::new(b"data to write");

    // Loop until the entire contents of the buffer are written to
    // the file.
    while buffer.has_remaining() {
        // Writes some prefix of the byte string, not necessarily
        // all of it.
        file.write_buf(&mut buffer).await?;
    }
    file.flush().await?;

    Ok(())
}
# }
```

## tokio::write_dac (function)

Requests permission to modify the pipe's discretionary access control list.

This corresponds to setting [`WRITE_DAC`] in dwOpenMode.

### tokio::write_dac (function) › Examples

```
use std::{io, os::windows::prelude::AsRawHandle, ptr};

use tokio::net::windows::named_pipe::ServerOptions;
use windows_sys::{
    Win32::Foundation::ERROR_SUCCESS,
    Win32::Security::DACL_SECURITY_INFORMATION,
    Win32::Security::Authorization::{SetSecurityInfo, SE_KERNEL_OBJECT},
};

const PIPE_NAME: &str = r"\\.\pipe\write_dac_pipe";

# #[tokio::main] async fn main() -> io::Result<()> {
let mut pipe_template = ServerOptions::new();
pipe_template.write_dac(true);
let pipe = pipe_template.create(PIPE_NAME)?;

unsafe {
    assert_eq!(
        ERROR_SUCCESS,
        SetSecurityInfo(
            pipe.as_raw_handle() as _,
            SE_KERNEL_OBJECT,
            DACL_SECURITY_INFORMATION,
            ptr::null_mut(),
            ptr::null_mut(),
            ptr::null_mut(),
            ptr::null_mut(),
        )
    );
}

# Ok(()) }
```

```
use std::{io, os::windows::prelude::AsRawHandle, ptr};

use tokio::net::windows::named_pipe::ServerOptions;
use windows_sys::{
    Win32::Foundation::ERROR_ACCESS_DENIED,
    Win32::Security::DACL_SECURITY_INFORMATION,
    Win32::Security::Authorization::{SetSecurityInfo, SE_KERNEL_OBJECT},
};

const PIPE_NAME: &str = r"\\.\pipe\write_dac_pipe_fail";

# #[tokio::main] async fn main() -> io::Result<()> {
let mut pipe_template = ServerOptions::new();
pipe_template.write_dac(false);
let pipe = pipe_template.create(PIPE_NAME)?;

unsafe {
    assert_eq!(
        ERROR_ACCESS_DENIED,
        SetSecurityInfo(
            pipe.as_raw_handle() as _,
            SE_KERNEL_OBJECT,
            DACL_SECURITY_INFORMATION,
            ptr::null_mut(),
            ptr::null_mut(),
            ptr::null_mut(),
            ptr::null_mut(),
        )
    );
}

# Ok(()) }
```

[`WRITE_DAC`]: https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createnamedpipea

## tokio::write_f32 (function)

Writes an 32-bit floating point type in big-endian order to the
underlying writer.

Equivalent to:

```ignore
async fn write_f32(&mut self, n: f32) -> io::Result<()>;
```

It is recommended to use a buffered writer to avoid excessive
syscalls.

### tokio::write_f32 (function) › Errors

This method returns the same errors as [`AsyncWriteExt::write_all`].

[`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all

### tokio::write_f32 (function) › Examples

Write 32-bit floating point type to a `AsyncWrite`:

```rust
use tokio::io::{self, AsyncWriteExt};

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut writer = Vec::new();

writer.write_f32(f32::MIN).await?;

assert_eq!(writer, vec![0xff, 0x7f, 0xff, 0xff]);
Ok(())
# }
```

## tokio::write_f32_le (function)

Writes an 32-bit floating point type in little-endian order to the
underlying writer.

Equivalent to:

```ignore
async fn write_f32_le(&mut self, n: f32) -> io::Result<()>;
```

It is recommended to use a buffered writer to avoid excessive
syscalls.

### tokio::write_f32_le (function) › Errors

This method returns the same errors as [`AsyncWriteExt::write_all`].

[`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all

### tokio::write_f32_le (function) › Examples

Write 32-bit floating point type to a `AsyncWrite`:

```rust
use tokio::io::{self, AsyncWriteExt};

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut writer = Vec::new();

writer.write_f32_le(f32::MIN).await?;

assert_eq!(writer, vec![0xff, 0xff, 0x7f, 0xff]);
Ok(())
# }
```

## tokio::write_f64 (function)

Writes an 64-bit floating point type in big-endian order to the
underlying writer.

Equivalent to:

```ignore
async fn write_f64(&mut self, n: f64) -> io::Result<()>;
```

It is recommended to use a buffered writer to avoid excessive
syscalls.

### tokio::write_f64 (function) › Errors

This method returns the same errors as [`AsyncWriteExt::write_all`].

[`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all

### tokio::write_f64 (function) › Examples

Write 64-bit floating point type to a `AsyncWrite`:

```rust
use tokio::io::{self, AsyncWriteExt};

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut writer = Vec::new();

writer.write_f64(f64::MIN).await?;

assert_eq!(writer, vec![
    0xff, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
]);
Ok(())
# }
```

## tokio::write_f64_le (function)

Writes an 64-bit floating point type in little-endian order to the
underlying writer.

Equivalent to:

```ignore
async fn write_f64_le(&mut self, n: f64) -> io::Result<()>;
```

It is recommended to use a buffered writer to avoid excessive
syscalls.

### tokio::write_f64_le (function) › Errors

This method returns the same errors as [`AsyncWriteExt::write_all`].

[`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all

### tokio::write_f64_le (function) › Examples

Write 64-bit floating point type to a `AsyncWrite`:

```rust
use tokio::io::{self, AsyncWriteExt};

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut writer = Vec::new();

writer.write_f64_le(f64::MIN).await?;

assert_eq!(writer, vec![
    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xef, 0xff
]);
Ok(())
# }
```

## tokio::write_i128 (function)

Writes an signed 128-bit integer in big-endian order to the
underlying writer.

Equivalent to:

```ignore
async fn write_i128(&mut self, n: i128) -> io::Result<()>;
```

It is recommended to use a buffered writer to avoid excessive
syscalls.

### tokio::write_i128 (function) › Errors

This method returns the same errors as [`AsyncWriteExt::write_all`].

[`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all

### tokio::write_i128 (function) › Examples

Write signed 128-bit integers to a `AsyncWrite`:

```rust
use tokio::io::{self, AsyncWriteExt};

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut writer = Vec::new();

writer.write_i128(i128::MIN).await?;

assert_eq!(writer, vec![
    0x80, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0
]);
Ok(())
# }
```

## tokio::write_i128_le (function)

Writes an signed 128-bit integer in little-endian order to the
underlying writer.

Equivalent to:

```ignore
async fn write_i128_le(&mut self, n: i128) -> io::Result<()>;
```

It is recommended to use a buffered writer to avoid excessive
syscalls.

### tokio::write_i128_le (function) › Errors

This method returns the same errors as [`AsyncWriteExt::write_all`].

[`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all

### tokio::write_i128_le (function) › Examples

Write signed 128-bit integers to a `AsyncWrite`:

```rust
use tokio::io::{self, AsyncWriteExt};

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut writer = Vec::new();

writer.write_i128_le(i128::MIN).await?;

assert_eq!(writer, vec![
    0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0x80
]);
Ok(())
# }
```

## tokio::write_i16 (function)

Writes a signed 16-bit integer in big-endian order to the
underlying writer.

Equivalent to:

```ignore
async fn write_i16(&mut self, n: i16) -> io::Result<()>;
```

It is recommended to use a buffered writer to avoid excessive
syscalls.

### tokio::write_i16 (function) › Errors

This method returns the same errors as [`AsyncWriteExt::write_all`].

[`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all

### tokio::write_i16 (function) › Examples

Write signed 16-bit integers to a `AsyncWrite`:

```rust
use tokio::io::{self, AsyncWriteExt};

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut writer = Vec::new();

writer.write_i16(193).await?;
writer.write_i16(-132).await?;

assert_eq!(writer, b"\x00\xc1\xff\x7c");
Ok(())
# }
```

## tokio::write_i16_le (function)

Writes a signed 16-bit integer in little-endian order to the
underlying writer.

Equivalent to:

```ignore
async fn write_i16_le(&mut self, n: i16) -> io::Result<()>;
```

It is recommended to use a buffered writer to avoid excessive
syscalls.

### tokio::write_i16_le (function) › Errors

This method returns the same errors as [`AsyncWriteExt::write_all`].

[`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all

### tokio::write_i16_le (function) › Examples

Write signed 16-bit integers to a `AsyncWrite`:

```rust
use tokio::io::{self, AsyncWriteExt};

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut writer = Vec::new();

writer.write_i16_le(193).await?;
writer.write_i16_le(-132).await?;

assert_eq!(writer, b"\xc1\x00\x7c\xff");
Ok(())
# }
```

## tokio::write_i32 (function)

Writes a signed 32-bit integer in big-endian order to the
underlying writer.

Equivalent to:

```ignore
async fn write_i32(&mut self, n: i32) -> io::Result<()>;
```

It is recommended to use a buffered writer to avoid excessive
syscalls.

### tokio::write_i32 (function) › Errors

This method returns the same errors as [`AsyncWriteExt::write_all`].

[`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all

### tokio::write_i32 (function) › Examples

Write signed 32-bit integers to a `AsyncWrite`:

```rust
use tokio::io::{self, AsyncWriteExt};

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut writer = Vec::new();

writer.write_i32(267).await?;
writer.write_i32(1205419366).await?;

assert_eq!(writer, b"\x00\x00\x01\x0b\x47\xd9\x3d\x66");
Ok(())
# }
```

## tokio::write_i32_le (function)

Writes a signed 32-bit integer in little-endian order to the
underlying writer.

Equivalent to:

```ignore
async fn write_i32_le(&mut self, n: i32) -> io::Result<()>;
```

It is recommended to use a buffered writer to avoid excessive
syscalls.

### tokio::write_i32_le (function) › Errors

This method returns the same errors as [`AsyncWriteExt::write_all`].

[`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all

### tokio::write_i32_le (function) › Examples

Write signed 32-bit integers to a `AsyncWrite`:

```rust
use tokio::io::{self, AsyncWriteExt};

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut writer = Vec::new();

writer.write_i32_le(267).await?;
writer.write_i32_le(1205419366).await?;

assert_eq!(writer, b"\x0b\x01\x00\x00\x66\x3d\xd9\x47");
Ok(())
# }
```

## tokio::write_i64 (function)

Writes an signed 64-bit integer in big-endian order to the
underlying writer.

Equivalent to:

```ignore
async fn write_i64(&mut self, n: i64) -> io::Result<()>;
```

It is recommended to use a buffered writer to avoid excessive
syscalls.

### tokio::write_i64 (function) › Errors

This method returns the same errors as [`AsyncWriteExt::write_all`].

[`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all

### tokio::write_i64 (function) › Examples

Write signed 64-bit integers to a `AsyncWrite`:

```rust
use tokio::io::{self, AsyncWriteExt};

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut writer = Vec::new();

writer.write_i64(i64::MIN).await?;
writer.write_i64(i64::MAX).await?;

assert_eq!(writer, b"\x80\x00\x00\x00\x00\x00\x00\x00\x7f\xff\xff\xff\xff\xff\xff\xff");
Ok(())
# }
```

## tokio::write_i64_le (function)

Writes an signed 64-bit integer in little-endian order to the
underlying writer.

Equivalent to:

```ignore
async fn write_i64_le(&mut self, n: i64) -> io::Result<()>;
```

It is recommended to use a buffered writer to avoid excessive
syscalls.

### tokio::write_i64_le (function) › Errors

This method returns the same errors as [`AsyncWriteExt::write_all`].

[`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all

### tokio::write_i64_le (function) › Examples

Write signed 64-bit integers to a `AsyncWrite`:

```rust
use tokio::io::{self, AsyncWriteExt};

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut writer = Vec::new();

writer.write_i64_le(i64::MIN).await?;
writer.write_i64_le(i64::MAX).await?;

assert_eq!(writer, b"\x00\x00\x00\x00\x00\x00\x00\x80\xff\xff\xff\xff\xff\xff\xff\x7f");
Ok(())
# }
```

## tokio::write_i8 (function)

Writes a signed 8-bit integer to the underlying writer.

Equivalent to:

```ignore
async fn write_i8(&mut self, n: i8) -> io::Result<()>;
```

It is recommended to use a buffered writer to avoid excessive
syscalls.

### tokio::write_i8 (function) › Errors

This method returns the same errors as [`AsyncWriteExt::write_all`].

[`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all

### tokio::write_i8 (function) › Examples

Write signed 8 bit integers to a `AsyncWrite`:

```rust
use tokio::io::{self, AsyncWriteExt};

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut writer = Vec::new();

writer.write_i8(-2).await?;
writer.write_i8(126).await?;

assert_eq!(writer, b"\xFE\x7E");
Ok(())
# }
```

## tokio::write_owned (function)

 Locks this `RwLock` with exclusive write access, causing the current
 task to yield until the lock has been acquired.

 The calling task will yield while other writers or readers currently
 have access to the lock.

 This method is identical to [`RwLock::write`], except that the returned
 guard references the `RwLock` with an [`Arc`] rather than by borrowing
 it. Therefore, the `RwLock` must be wrapped in an `Arc` to call this
 method, and the guard will live for the `'static` lifetime, as it keeps
 the `RwLock` alive by holding an `Arc`.

 Returns an RAII guard which will drop the write access of this `RwLock`
 when dropped.

### tokio::write_owned (function) › Cancel safety

 This method uses a queue to fairly distribute locks in the order they
 were requested. Cancelling a call to `write_owned` makes you lose your
 place in the queue.

### tokio::write_owned (function) › Examples

 ```
 use std::sync::Arc;
 use tokio::sync::RwLock;

 # #[tokio::main(flavor = "current_thread")]
 # async fn main() {
 let lock = Arc::new(RwLock::new(1));

 let mut n = lock.write_owned().await;
 *n = 2;
}
 ```

## tokio::write_owner (function)

Requests permission to modify the pipe's owner.

This corresponds to setting [`WRITE_OWNER`] in dwOpenMode.

[`WRITE_OWNER`]: https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createnamedpipea

## tokio::write_u128 (function)

Writes an unsigned 128-bit integer in big-endian order to the
underlying writer.

Equivalent to:

```ignore
async fn write_u128(&mut self, n: u128) -> io::Result<()>;
```

It is recommended to use a buffered writer to avoid excessive
syscalls.

### tokio::write_u128 (function) › Errors

This method returns the same errors as [`AsyncWriteExt::write_all`].

[`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all

### tokio::write_u128 (function) › Examples

Write unsigned 128-bit integers to a `AsyncWrite`:

```rust
use tokio::io::{self, AsyncWriteExt};

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut writer = Vec::new();

writer.write_u128(16947640962301618749969007319746179).await?;

assert_eq!(writer, vec![
    0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83,
    0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83
]);
Ok(())
# }
```

## tokio::write_u128_le (function)

Writes an unsigned 128-bit integer in little-endian order to the
underlying writer.

Equivalent to:

```ignore
async fn write_u128_le(&mut self, n: u128) -> io::Result<()>;
```

It is recommended to use a buffered writer to avoid excessive
syscalls.

### tokio::write_u128_le (function) › Errors

This method returns the same errors as [`AsyncWriteExt::write_all`].

[`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all

### tokio::write_u128_le (function) › Examples

Write unsigned 128-bit integers to a `AsyncWrite`:

```rust
use tokio::io::{self, AsyncWriteExt};

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut writer = Vec::new();

writer.write_u128_le(16947640962301618749969007319746179).await?;

assert_eq!(writer, vec![
    0x83, 0x86, 0x60, 0x4d, 0x95, 0x43, 0x03, 0x00,
    0x83, 0x86, 0x60, 0x4d, 0x95, 0x43, 0x03, 0x00,
]);
Ok(())
# }
```

## tokio::write_u16 (function)

Writes an unsigned 16-bit integer in big-endian order to the
underlying writer.

Equivalent to:

```ignore
async fn write_u16(&mut self, n: u16) -> io::Result<()>;
```

It is recommended to use a buffered writer to avoid excessive
syscalls.

### tokio::write_u16 (function) › Errors

This method returns the same errors as [`AsyncWriteExt::write_all`].

[`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all

### tokio::write_u16 (function) › Examples

Write unsigned 16-bit integers to a `AsyncWrite`:

```rust
use tokio::io::{self, AsyncWriteExt};

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut writer = Vec::new();

writer.write_u16(517).await?;
writer.write_u16(768).await?;

assert_eq!(writer, b"\x02\x05\x03\x00");
Ok(())
# }
```

## tokio::write_u16_le (function)

Writes an unsigned 16-bit integer in little-endian order to the
underlying writer.

Equivalent to:

```ignore
async fn write_u16_le(&mut self, n: u16) -> io::Result<()>;
```

It is recommended to use a buffered writer to avoid excessive
syscalls.

### tokio::write_u16_le (function) › Errors

This method returns the same errors as [`AsyncWriteExt::write_all`].

[`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all

### tokio::write_u16_le (function) › Examples

Write unsigned 16-bit integers to a `AsyncWrite`:

```rust
use tokio::io::{self, AsyncWriteExt};

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut writer = Vec::new();

writer.write_u16_le(517).await?;
writer.write_u16_le(768).await?;

assert_eq!(writer, b"\x05\x02\x00\x03");
Ok(())
# }
```

## tokio::write_u32 (function)

Writes an unsigned 32-bit integer in big-endian order to the
underlying writer.

Equivalent to:

```ignore
async fn write_u32(&mut self, n: u32) -> io::Result<()>;
```

It is recommended to use a buffered writer to avoid excessive
syscalls.

### tokio::write_u32 (function) › Errors

This method returns the same errors as [`AsyncWriteExt::write_all`].

[`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all

### tokio::write_u32 (function) › Examples

Write unsigned 32-bit integers to a `AsyncWrite`:

```rust
use tokio::io::{self, AsyncWriteExt};

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut writer = Vec::new();

writer.write_u32(267).await?;
writer.write_u32(1205419366).await?;

assert_eq!(writer, b"\x00\x00\x01\x0b\x47\xd9\x3d\x66");
Ok(())
# }
```

## tokio::write_u32_le (function)

Writes an unsigned 32-bit integer in little-endian order to the
underlying writer.

Equivalent to:

```ignore
async fn write_u32_le(&mut self, n: u32) -> io::Result<()>;
```

It is recommended to use a buffered writer to avoid excessive
syscalls.

### tokio::write_u32_le (function) › Errors

This method returns the same errors as [`AsyncWriteExt::write_all`].

[`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all

### tokio::write_u32_le (function) › Examples

Write unsigned 32-bit integers to a `AsyncWrite`:

```rust
use tokio::io::{self, AsyncWriteExt};

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut writer = Vec::new();

writer.write_u32_le(267).await?;
writer.write_u32_le(1205419366).await?;

assert_eq!(writer, b"\x0b\x01\x00\x00\x66\x3d\xd9\x47");
Ok(())
# }
```

## tokio::write_u64 (function)

Writes an unsigned 64-bit integer in big-endian order to the
underlying writer.

Equivalent to:

```ignore
async fn write_u64(&mut self, n: u64) -> io::Result<()>;
```

It is recommended to use a buffered writer to avoid excessive
syscalls.

### tokio::write_u64 (function) › Errors

This method returns the same errors as [`AsyncWriteExt::write_all`].

[`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all

### tokio::write_u64 (function) › Examples

Write unsigned 64-bit integers to a `AsyncWrite`:

```rust
use tokio::io::{self, AsyncWriteExt};

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut writer = Vec::new();

writer.write_u64(918733457491587).await?;
writer.write_u64(143).await?;

assert_eq!(writer, b"\x00\x03\x43\x95\x4d\x60\x86\x83\x00\x00\x00\x00\x00\x00\x00\x8f");
Ok(())
# }
```

## tokio::write_u64_le (function)

Writes an unsigned 64-bit integer in little-endian order to the
underlying writer.

Equivalent to:

```ignore
async fn write_u64_le(&mut self, n: u64) -> io::Result<()>;
```

It is recommended to use a buffered writer to avoid excessive
syscalls.

### tokio::write_u64_le (function) › Errors

This method returns the same errors as [`AsyncWriteExt::write_all`].

[`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all

### tokio::write_u64_le (function) › Examples

Write unsigned 64-bit integers to a `AsyncWrite`:

```rust
use tokio::io::{self, AsyncWriteExt};

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut writer = Vec::new();

writer.write_u64_le(918733457491587).await?;
writer.write_u64_le(143).await?;

assert_eq!(writer, b"\x83\x86\x60\x4d\x95\x43\x03\x00\x8f\x00\x00\x00\x00\x00\x00\x00");
Ok(())
# }
```

## tokio::write_u8 (function)

Writes an unsigned 8-bit integer to the underlying writer.

Equivalent to:

```ignore
async fn write_u8(&mut self, n: u8) -> io::Result<()>;
```

It is recommended to use a buffered writer to avoid excessive
syscalls.

### tokio::write_u8 (function) › Errors

This method returns the same errors as [`AsyncWriteExt::write_all`].

[`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all

### tokio::write_u8 (function) › Examples

Write unsigned 8 bit integers to a `AsyncWrite`:

```rust
use tokio::io::{self, AsyncWriteExt};

# #[tokio::main(flavor = "current_thread")]
# async fn main() -> io::Result<()> {
let mut writer = Vec::new();

writer.write_u8(2).await?;
writer.write_u8(5).await?;

assert_eq!(writer, b"\x02\x05");
Ok(())
# }
```

## tokio::write_vectored (function)

Like [`write`], except that it writes from a slice of buffers.

Equivalent to:

```ignore
async fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize>;
```

See [`AsyncWrite::poll_write_vectored`] for more details.

### tokio::write_vectored (function) › Cancel safety

This method is cancel safe. If it is used as a branch in
[`tokio::select!`](crate::select) and another branch completes
first, then it is guaranteed that no data was
written to this `AsyncWrite`.

### tokio::write_vectored (function) › Examples

```no_run
# #[cfg(not(target_family = "wasm"))]
# {
use tokio::io::{self, AsyncWriteExt};
use tokio::fs::File;
use std::io::IoSlice;

#[tokio::main]
async fn main() -> io::Result<()> {
    let mut file = File::create("foo.txt").await?;

    let bufs: &[_] = &[
        IoSlice::new(b"hello"),
        IoSlice::new(b" "),
        IoSlice::new(b"world"),
    ];

    file.write_vectored(&bufs).await?;
    file.flush().await?;

    Ok(())
}
# }
```

[`write`]: AsyncWriteExt::write

## tokio::writer (function)

Returns a reference to the inner writer.

## tokio::writer_mut (function)

Returns a mutable reference to the inner writer.

## tokio::writer_pin_mut (function)

Returns a pinned mutable reference to the inner writer.

