| <!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="generator" content="rustdoc"><meta name="description" content="The Tokio runtime."><meta name="keywords" content="rust, rustlang, rust-lang, runtime"><title>tokio::runtime - Rust</title><link rel="preload" as="font" type="font/woff2" crossorigin href="../../SourceSerif4-Regular.ttf.woff2"><link rel="preload" as="font" type="font/woff2" crossorigin href="../../FiraSans-Regular.woff2"><link rel="preload" as="font" type="font/woff2" crossorigin href="../../FiraSans-Medium.woff2"><link rel="preload" as="font" type="font/woff2" crossorigin href="../../SourceCodePro-Regular.ttf.woff2"><link rel="preload" as="font" type="font/woff2" crossorigin href="../../SourceSerif4-Bold.ttf.woff2"><link rel="preload" as="font" type="font/woff2" crossorigin href="../../SourceCodePro-Semibold.ttf.woff2"><link rel="stylesheet" href="../../normalize.css"><link rel="stylesheet" href="../../rustdoc.css" id="mainThemeStyle"><link rel="stylesheet" href="../../ayu.css" disabled><link rel="stylesheet" href="../../dark.css" disabled><link rel="stylesheet" href="../../light.css" id="themeStyle"><script id="default-settings" ></script><script src="../../storage.js"></script><script defer src="../../main.js"></script><noscript><link rel="stylesheet" href="../../noscript.css"></noscript><link rel="alternate icon" type="image/png" href="../../favicon-16x16.png"><link rel="alternate icon" type="image/png" href="../../favicon-32x32.png"><link rel="icon" type="image/svg+xml" href="../../favicon.svg"></head><body class="rustdoc mod"><!--[if lte IE 11]><div class="warning">This old browser is unsupported and will most likely display funky things.</div><![endif]--><nav class="mobile-topbar"><button class="sidebar-menu-toggle">☰</button><a class="sidebar-logo" href="../../tokio/index.html"><div class="logo-container"><img class="rust-logo" src="../../rust-logo.svg" alt="logo"></div></a><h2></h2></nav><nav class="sidebar"><a class="sidebar-logo" href="../../tokio/index.html"><div class="logo-container"><img class="rust-logo" src="../../rust-logo.svg" alt="logo"></div></a><h2 class="location"><a href="#">Module runtime</a></h2><div class="sidebar-elems"><section><ul class="block"><li><a href="#structs">Structs</a></li><li><a href="#enums">Enums</a></li></ul></section></div></nav><main><div class="width-limiter"><nav class="sub"><form class="search-form"><div class="search-container"><span></span><input class="search-input" name="search" autocomplete="off" spellcheck="false" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"><div id="help-button" title="help" tabindex="-1"><a href="../../help.html">?</a></div><div id="settings-menu" tabindex="-1"><a href="../../settings.html" title="settings"><img width="22" height="22" alt="Change settings" src="../../wheel.svg"></a></div></div></form></nav><section id="main-content" class="content"><div class="main-heading"><h1 class="fqn">Module <a href="../index.html">tokio</a>::<wbr><a class="mod" href="#">runtime</a><button id="copy-path" onclick="copy_path(this)" title="Copy item path to clipboard"><img src="../../clipboard.svg" width="19" height="18" alt="Copy item path"></button></h1><span class="out-of-band"><a class="srclink" href="../../src/tokio/runtime/mod.rs.html#1-261">source</a> · <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">[<span class="inner">−</span>]</a></span></div><details class="rustdoc-toggle top-doc" open><summary class="hideme"><span>Expand description</span></summary><div class="docblock"><p>The Tokio runtime.</p> |
| <p>Unlike other Rust programs, asynchronous applications require runtime |
| support. In particular, the following runtime services are necessary:</p> |
| <ul> |
| <li>An <strong>I/O event loop</strong>, called the driver, which drives I/O resources and |
| dispatches I/O events to tasks that depend on them.</li> |
| <li>A <strong>scheduler</strong> to execute <a href="../task/index.html">tasks</a> that use these I/O resources.</li> |
| <li>A <strong>timer</strong> for scheduling work to run after a set period of time.</li> |
| </ul> |
| <p>Tokio’s <a href="struct.Runtime.html"><code>Runtime</code></a> 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 <a href="struct.Runtime.html"><code>Runtime</code></a> manually, and a user may just use the |
| <a href="../attr.main.html"><code>tokio::main</code></a> attribute macro, which creates a <a href="struct.Runtime.html"><code>Runtime</code></a> under the hood.</p> |
| <h2 id="usage"><a href="#usage">Usage</a></h2> |
| <p>When no fine tuning is required, the <a href="../attr.main.html"><code>tokio::main</code></a> attribute macro can be |
| used.</p> |
| |
| <div class="example-wrap"><pre class="rust rust-example-rendered"><code><span class="kw">use </span>tokio::net::TcpListener; |
| <span class="kw">use </span>tokio::io::{AsyncReadExt, AsyncWriteExt}; |
| |
| <span class="attribute">#[tokio::main] |
| </span><span class="kw">async fn </span>main() -> <span class="prelude-ty">Result</span><(), Box<<span class="kw">dyn </span>std::error::Error>> { |
| <span class="kw">let </span>listener = TcpListener::bind(<span class="string">"127.0.0.1:8080"</span>).<span class="kw">await</span><span class="question-mark">?</span>; |
| |
| <span class="kw">loop </span>{ |
| <span class="kw">let </span>(<span class="kw-2">mut </span>socket, <span class="kw">_</span>) = listener.accept().<span class="kw">await</span><span class="question-mark">?</span>; |
| |
| tokio::spawn(<span class="kw">async move </span>{ |
| <span class="kw">let </span><span class="kw-2">mut </span>buf = [<span class="number">0</span>; <span class="number">1024</span>]; |
| |
| <span class="comment">// In a loop, read data from the socket and write the data back. |
| </span><span class="kw">loop </span>{ |
| <span class="kw">let </span>n = <span class="kw">match </span>socket.read(<span class="kw-2">&mut </span>buf).<span class="kw">await </span>{ |
| <span class="comment">// socket closed |
| </span><span class="prelude-val">Ok</span>(n) <span class="kw">if </span>n == <span class="number">0 </span>=> <span class="kw">return</span>, |
| <span class="prelude-val">Ok</span>(n) => n, |
| <span class="prelude-val">Err</span>(e) => { |
| <span class="macro">println!</span>(<span class="string">"failed to read from socket; err = {:?}"</span>, e); |
| <span class="kw">return</span>; |
| } |
| }; |
| |
| <span class="comment">// Write the data back |
| </span><span class="kw">if let </span><span class="prelude-val">Err</span>(e) = socket.write_all(<span class="kw-2">&</span>buf[<span class="number">0</span>..n]).<span class="kw">await </span>{ |
| <span class="macro">println!</span>(<span class="string">"failed to write to socket; err = {:?}"</span>, e); |
| <span class="kw">return</span>; |
| } |
| } |
| }); |
| } |
| }</code></pre></div> |
| <p>From within the context of the runtime, additional tasks are spawned using |
| the <a href="../task/fn.spawn.html"><code>tokio::spawn</code></a> function. Futures spawned using this function will be |
| executed on the same thread pool used by the <a href="struct.Runtime.html"><code>Runtime</code></a>.</p> |
| <p>A <a href="struct.Runtime.html"><code>Runtime</code></a> instance can also be used directly.</p> |
| |
| <div class="example-wrap"><pre class="rust rust-example-rendered"><code><span class="kw">use </span>tokio::net::TcpListener; |
| <span class="kw">use </span>tokio::io::{AsyncReadExt, AsyncWriteExt}; |
| <span class="kw">use </span>tokio::runtime::Runtime; |
| |
| <span class="kw">fn </span>main() -> <span class="prelude-ty">Result</span><(), Box<<span class="kw">dyn </span>std::error::Error>> { |
| <span class="comment">// Create the runtime |
| </span><span class="kw">let </span>rt = Runtime::new()<span class="question-mark">?</span>; |
| |
| <span class="comment">// Spawn the root task |
| </span>rt.block_on(<span class="kw">async </span>{ |
| <span class="kw">let </span>listener = TcpListener::bind(<span class="string">"127.0.0.1:8080"</span>).<span class="kw">await</span><span class="question-mark">?</span>; |
| |
| <span class="kw">loop </span>{ |
| <span class="kw">let </span>(<span class="kw-2">mut </span>socket, <span class="kw">_</span>) = listener.accept().<span class="kw">await</span><span class="question-mark">?</span>; |
| |
| tokio::spawn(<span class="kw">async move </span>{ |
| <span class="kw">let </span><span class="kw-2">mut </span>buf = [<span class="number">0</span>; <span class="number">1024</span>]; |
| |
| <span class="comment">// In a loop, read data from the socket and write the data back. |
| </span><span class="kw">loop </span>{ |
| <span class="kw">let </span>n = <span class="kw">match </span>socket.read(<span class="kw-2">&mut </span>buf).<span class="kw">await </span>{ |
| <span class="comment">// socket closed |
| </span><span class="prelude-val">Ok</span>(n) <span class="kw">if </span>n == <span class="number">0 </span>=> <span class="kw">return</span>, |
| <span class="prelude-val">Ok</span>(n) => n, |
| <span class="prelude-val">Err</span>(e) => { |
| <span class="macro">println!</span>(<span class="string">"failed to read from socket; err = {:?}"</span>, e); |
| <span class="kw">return</span>; |
| } |
| }; |
| |
| <span class="comment">// Write the data back |
| </span><span class="kw">if let </span><span class="prelude-val">Err</span>(e) = socket.write_all(<span class="kw-2">&</span>buf[<span class="number">0</span>..n]).<span class="kw">await </span>{ |
| <span class="macro">println!</span>(<span class="string">"failed to write to socket; err = {:?}"</span>, e); |
| <span class="kw">return</span>; |
| } |
| } |
| }); |
| } |
| }) |
| }</code></pre></div> |
| <h3 id="runtime-configurations"><a href="#runtime-configurations">Runtime Configurations</a></h3> |
| <p>Tokio provides multiple task scheduling strategies, suitable for different |
| applications. The <a href="struct.Builder.html">runtime builder</a> or <code>#[tokio::main]</code> attribute may be |
| used to select which scheduler to use.</p> |
| <h5 id="multi-thread-scheduler"><a href="#multi-thread-scheduler">Multi-Thread Scheduler</a></h5> |
| <p>The multi-thread scheduler executes futures on a <em>thread pool</em>, 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 <code>rt-multi-thread</code> |
| feature flag, and is selected by default:</p> |
| |
| <div class="example-wrap"><pre class="rust rust-example-rendered"><code><span class="kw">use </span>tokio::runtime; |
| |
| <span class="kw">let </span>threaded_rt = runtime::Runtime::new()<span class="question-mark">?</span>;</code></pre></div> |
| <p>Most applications should use the multi-thread scheduler, except in some |
| niche use-cases, such as when running only a single thread is required.</p> |
| <h5 id="current-thread-scheduler"><a href="#current-thread-scheduler">Current-Thread Scheduler</a></h5> |
| <p>The current-thread scheduler provides a <em>single-threaded</em> future executor. |
| All tasks will be created and executed on the current thread. This requires |
| the <code>rt</code> feature flag.</p> |
| |
| <div class="example-wrap"><pre class="rust rust-example-rendered"><code><span class="kw">use </span>tokio::runtime; |
| |
| <span class="kw">let </span>rt = runtime::Builder::new_current_thread() |
| .build()<span class="question-mark">?</span>;</code></pre></div> |
| <h5 id="resource-drivers"><a href="#resource-drivers">Resource drivers</a></h5> |
| <p>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 <a href="struct.Builder.html#method.enable_io"><code>Builder::enable_io</code></a> and <a href="struct.Builder.html#method.enable_time"><code>Builder::enable_time</code></a>. As a |
| shorthand, <a href="struct.Builder.html#method.enable_all"><code>Builder::enable_all</code></a> enables both resource drivers.</p> |
| <h3 id="lifetime-of-spawned-threads"><a href="#lifetime-of-spawned-threads">Lifetime of spawned threads</a></h3> |
| <p>The runtime may spawn threads depending on its configuration and usage. The |
| multi-thread scheduler spawns threads to schedule tasks and for <code>spawn_blocking</code> |
| calls.</p> |
| <p>While the <code>Runtime</code> is active, threads may shutdown after periods of being |
| idle. Once <code>Runtime</code> is dropped, all runtime threads are forcibly shutdown. |
| Any tasks that have not yet completed will be dropped.</p> |
| </div></details><h2 id="structs" class="small-section-header"><a href="#structs">Structs</a></h2><div class="item-table"><div class="item-row"><div class="item-left module-item"><a class="struct" href="struct.Builder.html" title="tokio::runtime::Builder struct">Builder</a></div><div class="item-right docblock-short">Builds Tokio Runtime with custom configuration values.</div></div><div class="item-row"><div class="item-left module-item"><a class="struct" href="struct.EnterGuard.html" title="tokio::runtime::EnterGuard struct">EnterGuard</a></div><div class="item-right docblock-short">Runtime context guard.</div></div><div class="item-row"><div class="item-left module-item"><a class="struct" href="struct.Handle.html" title="tokio::runtime::Handle struct">Handle</a></div><div class="item-right docblock-short">Handle to the runtime.</div></div><div class="item-row"><div class="item-left module-item"><a class="struct" href="struct.Runtime.html" title="tokio::runtime::Runtime struct">Runtime</a></div><div class="item-right docblock-short">The Tokio runtime.</div></div><div class="item-row"><div class="item-left module-item"><a class="struct" href="struct.TryCurrentError.html" title="tokio::runtime::TryCurrentError struct">TryCurrentError</a></div><div class="item-right docblock-short">Error returned by <code>try_current</code> when no Runtime has been started</div></div></div><h2 id="enums" class="small-section-header"><a href="#enums">Enums</a></h2><div class="item-table"><div class="item-row"><div class="item-left module-item"><a class="enum" href="enum.RuntimeFlavor.html" title="tokio::runtime::RuntimeFlavor enum">RuntimeFlavor</a></div><div class="item-right docblock-short">The flavor of a <code>Runtime</code>.</div></div></div></section></div></main><div id="rustdoc-vars" data-root-path="../../" data-current-crate="tokio" data-themes="ayu,dark,light" data-resource-suffix="" data-rustdoc-version="1.66.0-nightly (5c8bff74b 2022-10-21)" ></div></body></html> |