88 lines
12 KiB
HTML
88 lines
12 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="Runs the provided closure on a thread where blocking is acceptable."><title>spawn_blocking in tokio::task - Rust</title><script>if(window.location.protocol!=="file:")document.head.insertAdjacentHTML("beforeend","SourceSerif4-Regular-6b053e98.ttf.woff2,FiraSans-Italic-81dc35de.woff2,FiraSans-Regular-0fe48ade.woff2,FiraSans-MediumItalic-ccf7e434.woff2,FiraSans-Medium-e1aa3f0a.woff2,SourceCodePro-Regular-8badfe75.ttf.woff2,SourceCodePro-Semibold-aa29a496.ttf.woff2".split(",").map(f=>`<link rel="preload" as="font" type="font/woff2"href="../../static.files/${f}">`).join(""))</script><link rel="stylesheet" href="../../static.files/normalize-9960930a.css"><link rel="stylesheet" href="../../static.files/rustdoc-ca0dd0c4.css"><meta name="rustdoc-vars" data-root-path="../../" data-static-root-path="../../static.files/" data-current-crate="tokio" data-themes="" data-resource-suffix="" data-rustdoc-version="1.93.1 (01f6ddf75 2026-02-11) (Arch Linux rust 1:1.93.1-1)" data-channel="1.93.1" data-search-js="search-9e2438ea.js" data-stringdex-js="stringdex-a3946164.js" data-settings-js="settings-c38705f0.js" ><script src="../../static.files/storage-e2aeef58.js"></script><script defer src="sidebar-items.js"></script><script defer src="../../static.files/main-a410ff4d.js"></script><noscript><link rel="stylesheet" href="../../static.files/noscript-263c88ec.css"></noscript><link rel="alternate icon" type="image/png" href="../../static.files/favicon-32x32-eab170b8.png"><link rel="icon" type="image/svg+xml" href="../../static.files/favicon-044be391.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]--><rustdoc-topbar><h2><a href="#">spawn_blocking</a></h2></rustdoc-topbar><nav class="sidebar"><div class="sidebar-crate"><h2><a href="../../tokio/index.html">tokio</a><span class="version">1.49.0</span></h2></div><div class="sidebar-elems"><section id="rustdoc-toc"><h2 class="location"><a href="#">spawn_<wbr>blocking</a></h2><h3><a href="#">Sections</a></h3><ul class="block top-toc"><li><a href="#related-apis-and-patterns-for-bridging-asynchronous-and-blocking-code" title="Related APIs and patterns for bridging asynchronous and blocking code">Related APIs and patterns for bridging asynchronous and blocking code</a></li><li><a href="#examples" title="Examples">Examples</a></li></ul></section><div id="rustdoc-modnav"><h2><a href="index.html">In tokio::<wbr>task</a></h2></div></div></nav><div class="sidebar-resizer" title="Drag to resize sidebar"></div><main><div class="width-limiter"><section id="main-content" class="content"><div class="main-heading"><div class="rustdoc-breadcrumbs"><a href="../index.html">tokio</a>::<wbr><a href="index.html">task</a></div><h1>Function <span class="fn">spawn_<wbr>blocking</span> <button id="copy-path" title="Copy item path to clipboard">Copy item path</button></h1><rustdoc-toolbar></rustdoc-toolbar><span class="sub-heading"><a class="src" href="../../src/tokio/task/blocking.rs.html#205-211">Source</a> </span></div><pre class="rust item-decl"><code>pub fn spawn_blocking<F, R>(f: F) -> <a class="struct" href="struct.JoinHandle.html" title="struct tokio::task::JoinHandle">JoinHandle</a><R> <a href="#" class="tooltip" data-notable-ty="JoinHandle<R>">ⓘ</a><div class="where">where
|
||
F: <a class="trait" href="https://doc.rust-lang.org/1.93.1/core/ops/function/trait.FnOnce.html" title="trait core::ops::function::FnOnce">FnOnce</a>() -> R + <a class="trait" href="https://doc.rust-lang.org/1.93.1/core/marker/trait.Send.html" title="trait core::marker::Send">Send</a> + 'static,
|
||
R: <a class="trait" href="https://doc.rust-lang.org/1.93.1/core/marker/trait.Send.html" title="trait core::marker::Send">Send</a> + 'static,</div></code></pre><details class="toggle top-doc" open><summary class="hideme"><span>Expand description</span></summary><div class="docblock"><p>Runs the provided closure on a thread where blocking is acceptable.</p>
|
||
<p>In general, issuing a blocking call or performing a lot of compute in a
|
||
future without yielding is problematic, as it may prevent the executor from
|
||
driving other futures forward. This function runs the provided closure on a
|
||
thread dedicated to blocking operations. See the <a href="../index.html#cpu-bound-tasks-and-blocking-code">CPU-bound tasks and
|
||
blocking code</a> section for more information.</p>
|
||
<p>Tokio will spawn more blocking threads when they are requested through this
|
||
function until the upper limit configured on the <a href="../runtime/struct.Builder.html" title="struct tokio::runtime::Builder"><code>Builder</code></a> is reached.
|
||
After reaching the upper limit, the tasks are put in a queue.
|
||
The thread limit is very large by default, because <code>spawn_blocking</code> is often
|
||
used for various kinds of IO operations that cannot be performed
|
||
asynchronously. When you run CPU-bound code using <code>spawn_blocking</code>, you
|
||
should keep this large upper limit in mind. When running many CPU-bound
|
||
computations, a semaphore or some other synchronization primitive should be
|
||
used to limit the number of computation executed in parallel. Specialized
|
||
CPU-bound executors, such as <a href="https://docs.rs/rayon">rayon</a>, may also be a good fit.</p>
|
||
<p>This function is intended for non-async operations that eventually finish on
|
||
their own. If you want to spawn an ordinary thread, you should use
|
||
<a href="https://doc.rust-lang.org/1.93.1/std/thread/functions/fn.spawn.html" title="fn std::thread::functions::spawn"><code>thread::spawn</code></a> instead.</p>
|
||
<p>Be aware that tasks spawned using <code>spawn_blocking</code> cannot be aborted
|
||
because they are not async. If you call <a href="struct.JoinHandle.html#method.abort" title="method tokio::task::JoinHandle::abort"><code>abort</code></a> on a <code>spawn_blocking</code>
|
||
task, then this <em>will not have any effect</em>, and the task will continue
|
||
running normally. The exception is if the task has not started running
|
||
yet; in that case, calling <code>abort</code> may prevent the task from starting.</p>
|
||
<p>When you shut down the executor, it will attempt to <code>abort</code> all tasks
|
||
including <code>spawn_blocking</code> tasks. However, <code>spawn_blocking</code> tasks
|
||
cannot be aborted once they start running, which means that runtime
|
||
shutdown will wait indefinitely for all started <code>spawn_blocking</code> to
|
||
finish running. You can use <a href="../runtime/struct.Runtime.html#method.shutdown_timeout" title="method tokio::runtime::Runtime::shutdown_timeout"><code>shutdown_timeout</code></a> to stop waiting for
|
||
them after a certain timeout. Be aware that this will still not cancel
|
||
the tasks — they are simply allowed to keep running after the method
|
||
returns. It is possible for a blocking task to be cancelled if it has
|
||
not yet started running, but this is not guaranteed.</p>
|
||
<p>Note that if you are using the single threaded runtime, this function will
|
||
still spawn additional threads for blocking operations. The current-thread
|
||
scheduler’s single thread is only used for asynchronous code.</p>
|
||
<h2 id="related-apis-and-patterns-for-bridging-asynchronous-and-blocking-code"><a class="doc-anchor" href="#related-apis-and-patterns-for-bridging-asynchronous-and-blocking-code">§</a>Related APIs and patterns for bridging asynchronous and blocking code</h2>
|
||
<p>In simple cases, it is sufficient to have the closure accept input
|
||
parameters at creation time and return a single value (or struct/tuple, etc.).</p>
|
||
<p>For more complex situations in which it is desirable to stream data to or from
|
||
the synchronous context, the <a href="../sync/mpsc/index.html" title="mod tokio::sync::mpsc"><code>mpsc channel</code></a> has <code>blocking_send</code> and
|
||
<code>blocking_recv</code> methods for use in non-async code such as the thread created
|
||
by <code>spawn_blocking</code>.</p>
|
||
<p>Another option is <a href="https://docs.rs/tokio-util/latest/tokio_util/io/struct.SyncIoBridge.html"><code>SyncIoBridge</code></a> for cases where the synchronous context
|
||
is operating on byte streams. For example, you might use an asynchronous
|
||
HTTP client such as <a href="https://docs.rs/hyper">hyper</a> to fetch data, but perform complex parsing
|
||
of the payload body using a library written for synchronous I/O.</p>
|
||
<p>Finally, see also <a href="https://tokio.rs/tokio/topics/bridging">Bridging with sync code</a> for discussions
|
||
around the opposite case of using Tokio as part of a larger synchronous
|
||
codebase.</p>
|
||
<h2 id="examples"><a class="doc-anchor" href="#examples">§</a>Examples</h2>
|
||
<p>Pass an input value and receive result of computation:</p>
|
||
|
||
<div class="example-wrap"><pre class="rust rust-example-rendered"><code><span class="kw">use </span>tokio::task;
|
||
|
||
<span class="comment">// Initial input
|
||
</span><span class="kw">let </span><span class="kw-2">mut </span>v = <span class="string">"Hello, "</span>.to_string();
|
||
<span class="kw">let </span>res = task::spawn_blocking(<span class="kw">move </span>|| {
|
||
<span class="comment">// Stand-in for compute-heavy work or using synchronous APIs
|
||
</span>v.push_str(<span class="string">"world"</span>);
|
||
<span class="comment">// Pass ownership of the value back to the asynchronous context
|
||
</span>v
|
||
}).<span class="kw">await</span><span class="question-mark">?</span>;
|
||
|
||
<span class="comment">// `res` is the value returned from the thread
|
||
</span><span class="macro">assert_eq!</span>(res.as_str(), <span class="string">"Hello, world"</span>);</code></pre></div>
|
||
<p>Use a channel:</p>
|
||
|
||
<div class="example-wrap"><pre class="rust rust-example-rendered"><code><span class="kw">use </span>tokio::task;
|
||
<span class="kw">use </span>tokio::sync::mpsc;
|
||
|
||
<span class="kw">let </span>(tx, <span class="kw-2">mut </span>rx) = mpsc::channel(<span class="number">2</span>);
|
||
<span class="kw">let </span>start = <span class="number">5</span>;
|
||
<span class="kw">let </span>worker = task::spawn_blocking(<span class="kw">move </span>|| {
|
||
<span class="kw">for </span>x <span class="kw">in </span><span class="number">0</span>..<span class="number">10 </span>{
|
||
<span class="comment">// Stand in for complex computation
|
||
</span>tx.blocking_send(start + x).unwrap();
|
||
}
|
||
});
|
||
|
||
<span class="kw">let </span><span class="kw-2">mut </span>acc = <span class="number">0</span>;
|
||
<span class="kw">while let </span><span class="prelude-val">Some</span>(v) = rx.recv().<span class="kw">await </span>{
|
||
acc += v;
|
||
}
|
||
<span class="macro">assert_eq!</span>(acc, <span class="number">95</span>);
|
||
worker.<span class="kw">await</span>.unwrap();</code></pre></div></div></details><script type="text/json" id="notable-traits-data">{"JoinHandle<R>":"<h3>Notable traits for <code><a class=\"struct\" href=\"struct.JoinHandle.html\" title=\"struct tokio::task::JoinHandle\">JoinHandle</a><T></code></h3><pre><code><div class=\"where\">impl<T> <a class=\"trait\" href=\"https://doc.rust-lang.org/1.93.1/core/future/future/trait.Future.html\" title=\"trait core::future::future::Future\">Future</a> for <a class=\"struct\" href=\"struct.JoinHandle.html\" title=\"struct tokio::task::JoinHandle\">JoinHandle</a><T></div><div class=\"where\"> type <a href=\"https://doc.rust-lang.org/1.93.1/core/future/future/trait.Future.html#associatedtype.Output\" class=\"associatedtype\">Output</a> = <a class=\"enum\" href=\"https://doc.rust-lang.org/1.93.1/core/result/enum.Result.html\" title=\"enum core::result::Result\">Result</a><T, <a class=\"struct\" href=\"struct.JoinError.html\" title=\"struct tokio::task::JoinError\">JoinError</a>>;</div>"}</script></section></div></main></body></html> |