What is the runtime?
The runtime bundles three critical services:- I/O event loop - Drives I/O resources and dispatches events to tasks
- Scheduler - Executes tasks that use I/O resources
- Timer - Schedules work to run after a set period of time
Runtime type.
Getting started
Most applications use the#[tokio::main] attribute macro, which creates a runtime automatically:
Choosing a runtime scheduler
Tokio provides multiple schedulers for different use cases:Multi-thread scheduler
The multi-thread scheduler executes futures on a thread pool using a work-stealing strategy. By default, it spawns one worker thread per CPU core.rt-multi-thread feature flag.
Current-thread scheduler
The current-thread scheduler provides a single-threaded executor. All tasks are created and executed on the current thread.rt feature flag.
Use this scheduler for single-threaded applications or when you need to execute
!Send futures.Runtime configuration
TheBuilder provides extensive configuration options:
Enabling resource drivers
When configuring a runtime manually, resource drivers must be enabled explicitly:Driving the runtime
A runtime can only execute tasks when it’s running:- Multi-threaded runtime - Always running because it spawns worker threads
- Current-thread runtime - Only executes tasks when you call
Runtime::block_on
Runtime fairness guarantees
Tokio provides fairness guarantees to prevent task starvation:If the total number of tasks does not grow without bound, and no task is blocking the thread, then tasks are guaranteed to be scheduled fairly.The runtime will:
- Schedule tasks cooperatively at
.awaitpoints - Check for I/O and timer events periodically
- Prevent any single task from monopolizing the scheduler
Multi-thread runtime behavior
The multi-thread runtime maintains:- One global queue shared across all workers
- One local queue per worker thread (max 256 tasks)
- A LIFO slot optimization for recently woken tasks
Current-thread runtime behavior
The current-thread runtime maintains:- One global FIFO queue
- One local FIFO queue
global_queue_interval).
Shutdown behavior
Shutting down the runtime happens by:- Dropping the
Runtimevalue - Calling
shutdown_background()orshutdown_timeout()
spawn_blocking will run until completion:
NUMA awareness
The Tokio runtime is not NUMA (Non-Uniform Memory Access) aware. For better performance on NUMA systems, consider running multiple independent runtimes.
Feature flags
rt- Enables the current-thread schedulerrt-multi-thread- Enables the multi-threaded schedulermacros- Enables#[tokio::main]and#[tokio::test]macros