Module tokio::runtime [] [src]

A batteries included runtime for applications using Tokio.

Applications using Tokio require some runtime support in order to work:

  • A reactor to drive I/O resources.
  • An executor to execute tasks that use these I/O resources.

While it is possible to setup each component manually, this involves a bunch of boilerplate.

Runtime bundles all of these various runtime components into a single handle that can be started and shutdown together, eliminating the necessary boilerplate to run a Tokio application.

Most applications wont need to use Runtime directly. Instead, they will use the run function, which uses Runtime under the hood.

Creating a Runtime does the following:

  • Spawn a background thread running a [Reactor] instance.
  • Start a ThreadPool for executing futures.

The thread pool uses a work-stealing strategy and is configured to start a worker thread for each CPU core available on the system. This tends to be the ideal setup for Tokio applications.

Usage

Most applications will use the run function. This takes a future to "seed" the application, blocking the thread until the runtime becomes idle.

use tokio::net::TcpListener;

let listener = TcpListener::bind(&addr).unwrap();

let server = listener.incoming()
    .map_err(|e| println!("error = {:?}", e))
    .for_each(|socket| {
        tokio::spawn(process(socket))
    });

tokio::run(server);

In this function, the run function blocks until the runtime becomes idle. See shutdown_on_idle for more shutdown details.

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.

use tokio::runtime::Runtime;
use tokio::net::TcpListener;

let listener = TcpListener::bind(&addr).unwrap();

let server = listener.incoming()
    .map_err(|e| println!("error = {:?}", e))
    .for_each(|socket| {
        tokio::spawn(process(socket))
    });

// Create the runtime
let mut rt = Runtime::new().unwrap();

// Spawn the server task
rt.spawn(server);

// Wait until the runtime becomes idle and shut it down.
rt.shutdown_on_idle()
    .wait().unwrap();

Structs

Runtime

Handle to the Tokio runtime.

Shutdown

A future that resolves when the Tokio Runtime is shut down.

TaskExecutor

Executes futures on the runtime

Functions

run

Start the Tokio runtime using the supplied future to bootstrap execution.