| <!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="Spawns a new asynchronous task, returning a `JoinHandle` for it."><meta name="keywords" content="rust, rustlang, rust-lang, spawn"><title>spawn in tokio - 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="sidebar-items.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 fn"><!--[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><div class="sidebar-elems"><h2><a href="index.html">In tokio</a></h2></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">Function <a href="index.html">tokio</a>::<wbr><a class="fn" href="#">spawn</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/task/spawn.rs.html#161-173">source</a> · <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">[<span class="inner">−</span>]</a></span></div><div class="item-decl"><pre class="rust fn"><code>pub fn spawn<T>(future: T) -> <a class="struct" href="task/struct.JoinHandle.html" title="struct tokio::task::JoinHandle">JoinHandle</a><T::Output><span class="notable-traits"><span class="notable-traits-tooltip">ⓘ<span class="notable-traits-tooltiptext"><span class="docblock"><span class="notable">Notable traits for <a class="struct" href="task/struct.JoinHandle.html" title="struct tokio::task::JoinHandle">JoinHandle</a><T></span><code class="content"><span class="where fmt-newline">impl<T> Future for <a class="struct" href="task/struct.JoinHandle.html" title="struct tokio::task::JoinHandle">JoinHandle</a><T></span><span class="where fmt-newline"> type <a class="associatedtype">Output</a> = Result<T, <a class="struct" href="task/struct.JoinError.html" title="struct tokio::task::JoinError">JoinError</a>>;</span></code></span></span></span></span><span class="where fmt-newline">where<br> T: Future + Send + 'static,<br> T::Output: Send + 'static,</span></code></pre></div><details class="rustdoc-toggle top-doc" open><summary class="hideme"><span>Expand description</span></summary><div class="docblock"><p>Spawns a new asynchronous task, returning a |
| <a href="task/struct.JoinHandle.html"><code>JoinHandle</code></a> for it.</p> |
| <p>You do not have to <code>.await</code> the returned <code>JoinHandle</code> to make the |
| provided future start execution. It will start running in the background |
| immediately when <code>spawn</code> is called.</p> |
| <p>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 |
| <a href="runtime/struct.Runtime.html"><code>Runtime</code></a> configuration.</p> |
| <p>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.</p> |
| <p>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 <a href="runtime/struct.Runtime.html#method.enter"><code>Runtime::enter</code></a> method.</p> |
| <h2 id="examples"><a href="#examples">Examples</a></h2> |
| <p>In this example, a server is started and <code>spawn</code> is used to start a new task |
| that processes each received connection.</p> |
| |
| <div class="example-wrap"><pre class="rust rust-example-rendered"><code><span class="kw">use </span>tokio::net::{TcpListener, TcpStream}; |
| |
| <span class="kw">use </span>std::io; |
| |
| <span class="kw">async fn </span>process(socket: TcpStream) { |
| <span class="comment">// ... |
| </span>} |
| |
| <span class="attribute">#[tokio::main] |
| </span><span class="kw">async fn </span>main() -> io::Result<()> { |
| <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>(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="comment">// Process each socket concurrently. |
| </span>process(socket).<span class="kw">await |
| </span>}); |
| } |
| }</code></pre></div> |
| <p>To run multiple tasks in parallel and receive their results, join |
| handles can be stored in a vector.</p> |
| |
| <div class="example-wrap"><pre class="rust rust-example-rendered"><code><span class="kw">async fn </span>my_background_op(id: i32) -> String { |
| <span class="kw">let </span>s = <span class="macro">format!</span>(<span class="string">"Starting background task {}."</span>, id); |
| <span class="macro">println!</span>(<span class="string">"{}"</span>, s); |
| s |
| } |
| |
| <span class="kw">let </span>ops = <span class="macro">vec!</span>[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]; |
| <span class="kw">let </span><span class="kw-2">mut </span>tasks = Vec::with_capacity(ops.len()); |
| <span class="kw">for </span>op <span class="kw">in </span>ops { |
| <span class="comment">// This call will make them start running in the background |
| // immediately. |
| </span>tasks.push(tokio::spawn(my_background_op(op))); |
| } |
| |
| <span class="kw">let </span><span class="kw-2">mut </span>outputs = Vec::with_capacity(tasks.len()); |
| <span class="kw">for </span>task <span class="kw">in </span>tasks { |
| outputs.push(task.<span class="kw">await</span>.unwrap()); |
| } |
| <span class="macro">println!</span>(<span class="string">"{:?}"</span>, outputs);</code></pre></div> |
| <p>This example pushes the tasks to <code>outputs</code> in the order they were |
| started in. If you do not care about the ordering of the outputs, then |
| you can also use a <a href="task/struct.JoinSet.html"><code>JoinSet</code></a>.</p> |
| <h2 id="panics"><a href="#panics">Panics</a></h2> |
| <p>Panics if called from <strong>outside</strong> of the Tokio runtime.</p> |
| <h2 id="using-send-values-from-a-task"><a href="#using-send-values-from-a-task">Using <code>!Send</code> values from a task</a></h2> |
| <p>The task supplied to <code>spawn</code> must implement <code>Send</code>. However, it is |
| possible to <strong>use</strong> <code>!Send</code> values from the task as long as they only |
| exist between calls to <code>.await</code>.</p> |
| <p>For example, this will work:</p> |
| |
| <div class="example-wrap"><pre class="rust rust-example-rendered"><code><span class="kw">use </span>tokio::task; |
| |
| <span class="kw">use </span>std::rc::Rc; |
| |
| <span class="kw">fn </span>use_rc(rc: Rc<()>) { |
| <span class="comment">// Do stuff w/ rc |
| </span>} |
| |
| <span class="attribute">#[tokio::main] |
| </span><span class="kw">async fn </span>main() { |
| tokio::spawn(<span class="kw">async </span>{ |
| <span class="comment">// Force the `Rc` to stay in a scope with no `.await` |
| </span>{ |
| <span class="kw">let </span>rc = Rc::new(()); |
| use_rc(rc.clone()); |
| } |
| |
| task::yield_now().<span class="kw">await</span>; |
| }).<span class="kw">await</span>.unwrap(); |
| }</code></pre></div> |
| <p>This will <strong>not</strong> work:</p> |
| |
| <div class="example-wrap compile_fail"><div class='tooltip'>ⓘ</div><pre class="rust rust-example-rendered"><code><span class="kw">use </span>tokio::task; |
| |
| <span class="kw">use </span>std::rc::Rc; |
| |
| <span class="kw">fn </span>use_rc(rc: Rc<()>) { |
| <span class="comment">// Do stuff w/ rc |
| </span>} |
| |
| <span class="attribute">#[tokio::main] |
| </span><span class="kw">async fn </span>main() { |
| tokio::spawn(<span class="kw">async </span>{ |
| <span class="kw">let </span>rc = Rc::new(()); |
| |
| task::yield_now().<span class="kw">await</span>; |
| |
| use_rc(rc.clone()); |
| }).<span class="kw">await</span>.unwrap(); |
| }</code></pre></div> |
| <p>Holding on to a <code>!Send</code> value across calls to <code>.await</code> will result in |
| an unfriendly compile error message similar to:</p> |
| <div class="example-wrap"><pre class="language-text"><code>`[... some type ...]` cannot be sent between threads safely</code></pre></div> |
| <p>or:</p> |
| <div class="example-wrap"><pre class="language-text"><code>error[E0391]: cycle detected when processing `main`</code></pre></div></div></details></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> |