144 lines
18 KiB
HTML
144 lines
18 KiB
HTML
<!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" type="text/css" href="../../normalize.css"><link rel="stylesheet" type="text/css" href="../../rustdoc.css" id="mainThemeStyle"><link rel="stylesheet" type="text/css" href="../../ayu.css" disabled><link rel="stylesheet" type="text/css" href="../../dark.css" disabled><link rel="stylesheet" type="text/css" href="../../light.css" id="themeStyle"><script id="default-settings" ></script><script src="../../storage.js"></script><script src="../../crates.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="sidebar"><div class="sidebar-menu" role="button">☰</div><a class="sidebar-logo" href="../../tokio/index.html"><div class="logo-container"><img class="rust-logo" src="../../rust-logo.png" alt="logo"></div>
|
||
</a><h2 class="location">Module runtime</h2><div class="sidebar-elems"><div class="block items"><ul><li><a href="#structs">Structs</a></li></ul></div><div id="sidebar-vars" data-name="runtime" data-ty="mod" data-relpath="./"></div><script defer src="./sidebar-items.js"></script></div></nav><main><div class="width-limiter"><div class="sub-container"><a class="sub-logo-container" href="../../tokio/index.html"><img class="rust-logo" src="../../rust-logo.png" alt="logo"></a><nav class="sub"><div class="theme-picker"><button id="theme-picker" aria-label="Pick another theme!" aria-haspopup="menu" title="themes"><img width="18" height="18" alt="Pick another theme!" src="../../brush.svg"></button><div id="theme-choices" role="menu"></div></div><form class="search-form"><div class="search-container"><div><select id="crate-search"><option value="All crates">All crates</option></select><input class="search-input" name="search" autocomplete="off" spellcheck="false" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"></div><button type="button" id="help-button" title="help">?</button><a id="settings-menu" href="../../settings.html" title="settings"><img width="18" height="18" alt="Change settings" src="../../wheel.svg"></a></div></form></nav></div><section id="main-content" class="content"><h1 class="fqn"><span class="in-band">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></span><span class="out-of-band"><span id="render-detail"><a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">[<span class="inner">−</span>]</a></span><a class="srclink" href="../../src/tokio/runtime/mod.rs.html#1-623" title="goto source code">[src]</a></span></h1><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" class="section-header"><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> <span class="ident">tokio::net::TcpListener</span>;
|
||
<span class="kw">use</span> <span class="ident">tokio::io</span>::{<span class="ident">AsyncReadExt</span>, <span class="ident">AsyncWriteExt</span>};
|
||
|
||
<span class="attribute">#[<span class="ident">tokio::main</span>]</span>
|
||
<span class="kw">async</span> <span class="kw">fn</span> <span class="ident">main</span>() -> <span class="prelude-ty">Result</span><span class="op"><</span>(), <span class="ident">Box</span><span class="op"><</span><span class="kw">dyn</span> <span class="ident">std::error::Error</span><span class="op">></span><span class="op">></span> {
|
||
<span class="kw">let</span> <span class="ident">listener</span> <span class="op">=</span> <span class="ident">TcpListener::bind</span>(<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> <span class="ident">socket</span>, <span class="kw">_</span>) <span class="op">=</span> <span class="ident">listener</span>.<span class="ident">accept</span>().<span class="kw">await</span><span class="question-mark">?</span>;
|
||
|
||
<span class="ident">tokio::spawn</span>(<span class="kw">async</span> <span class="kw">move</span> {
|
||
<span class="kw">let</span> <span class="kw-2">mut</span> <span class="ident">buf</span> <span class="op">=</span> [<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> <span class="ident">n</span> <span class="op">=</span> <span class="kw">match</span> <span class="ident">socket</span>.<span class="ident">read</span>(<span class="kw-2">&mut</span> <span class="ident">buf</span>).<span class="kw">await</span> {
|
||
<span class="comment">// socket closed</span>
|
||
<span class="prelude-val">Ok</span>(<span class="ident">n</span>) <span class="kw">if</span> <span class="ident">n</span> <span class="op">==</span> <span class="number">0</span> => <span class="kw">return</span>,
|
||
<span class="prelude-val">Ok</span>(<span class="ident">n</span>) => <span class="ident">n</span>,
|
||
<span class="prelude-val">Err</span>(<span class="ident">e</span>) => {
|
||
<span class="macro">println!</span>(<span class="string">"failed to read from socket; err = {:?}"</span>, <span class="ident">e</span>);
|
||
<span class="kw">return</span>;
|
||
}
|
||
};
|
||
|
||
<span class="comment">// Write the data back</span>
|
||
<span class="kw">if</span> <span class="kw">let</span> <span class="prelude-val">Err</span>(<span class="ident">e</span>) <span class="op">=</span> <span class="ident">socket</span>.<span class="ident">write_all</span>(<span class="kw-2">&</span><span class="ident">buf</span>[<span class="number">0</span>..<span class="ident">n</span>]).<span class="kw">await</span> {
|
||
<span class="macro">println!</span>(<span class="string">"failed to write to socket; err = {:?}"</span>, <span class="ident">e</span>);
|
||
<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> <span class="ident">tokio::net::TcpListener</span>;
|
||
<span class="kw">use</span> <span class="ident">tokio::io</span>::{<span class="ident">AsyncReadExt</span>, <span class="ident">AsyncWriteExt</span>};
|
||
<span class="kw">use</span> <span class="ident">tokio::runtime::Runtime</span>;
|
||
|
||
<span class="kw">fn</span> <span class="ident">main</span>() -> <span class="prelude-ty">Result</span><span class="op"><</span>(), <span class="ident">Box</span><span class="op"><</span><span class="kw">dyn</span> <span class="ident">std::error::Error</span><span class="op">></span><span class="op">></span> {
|
||
<span class="comment">// Create the runtime</span>
|
||
<span class="kw">let</span> <span class="ident">rt</span> <span class="op">=</span> <span class="ident">Runtime::new</span>()<span class="question-mark">?</span>;
|
||
|
||
<span class="comment">// Spawn the root task</span>
|
||
<span class="ident">rt</span>.<span class="ident">block_on</span>(<span class="kw">async</span> {
|
||
<span class="kw">let</span> <span class="ident">listener</span> <span class="op">=</span> <span class="ident">TcpListener::bind</span>(<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> <span class="ident">socket</span>, <span class="kw">_</span>) <span class="op">=</span> <span class="ident">listener</span>.<span class="ident">accept</span>().<span class="kw">await</span><span class="question-mark">?</span>;
|
||
|
||
<span class="ident">tokio::spawn</span>(<span class="kw">async</span> <span class="kw">move</span> {
|
||
<span class="kw">let</span> <span class="kw-2">mut</span> <span class="ident">buf</span> <span class="op">=</span> [<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> <span class="ident">n</span> <span class="op">=</span> <span class="kw">match</span> <span class="ident">socket</span>.<span class="ident">read</span>(<span class="kw-2">&mut</span> <span class="ident">buf</span>).<span class="kw">await</span> {
|
||
<span class="comment">// socket closed</span>
|
||
<span class="prelude-val">Ok</span>(<span class="ident">n</span>) <span class="kw">if</span> <span class="ident">n</span> <span class="op">==</span> <span class="number">0</span> => <span class="kw">return</span>,
|
||
<span class="prelude-val">Ok</span>(<span class="ident">n</span>) => <span class="ident">n</span>,
|
||
<span class="prelude-val">Err</span>(<span class="ident">e</span>) => {
|
||
<span class="macro">println!</span>(<span class="string">"failed to read from socket; err = {:?}"</span>, <span class="ident">e</span>);
|
||
<span class="kw">return</span>;
|
||
}
|
||
};
|
||
|
||
<span class="comment">// Write the data back</span>
|
||
<span class="kw">if</span> <span class="kw">let</span> <span class="prelude-val">Err</span>(<span class="ident">e</span>) <span class="op">=</span> <span class="ident">socket</span>.<span class="ident">write_all</span>(<span class="kw-2">&</span><span class="ident">buf</span>[<span class="number">0</span>..<span class="ident">n</span>]).<span class="kw">await</span> {
|
||
<span class="macro">println!</span>(<span class="string">"failed to write to socket; err = {:?}"</span>, <span class="ident">e</span>);
|
||
<span class="kw">return</span>;
|
||
}
|
||
}
|
||
});
|
||
}
|
||
})
|
||
}</code></pre></div>
|
||
<h3 id="runtime-configurations" class="section-header"><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" class="section-header"><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> <span class="ident">tokio::runtime</span>;
|
||
|
||
<span class="kw">let</span> <span class="ident">threaded_rt</span> <span class="op">=</span> <span class="ident">runtime::Runtime::new</span>()<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" class="section-header"><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> <span class="ident">tokio::runtime</span>;
|
||
|
||
<span class="kw">let</span> <span class="ident">basic_rt</span> <span class="op">=</span> <span class="ident">runtime::Builder::new_current_thread</span>()
|
||
.<span class="ident">build</span>()<span class="question-mark">?</span>;</code></pre></div>
|
||
<h5 id="resource-drivers" class="section-header"><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" class="section-header"><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"><p>Builds Tokio Runtime with custom configuration values.</p>
|
||
</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"><p>Runtime context guard.</p>
|
||
</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"><p>Handle to the runtime.</p>
|
||
</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"><p>The Tokio runtime.</p>
|
||
</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"><p>Error returned by <code>try_current</code> when no Runtime has been started</p>
|
||
</div></div></div></section><section id="search" class="content hidden"></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.59.0 (9d1b2106e 2022-02-23)" ></div>
|
||
</body></html> |