Async: Tokio, blocking, cancellation, and structured concurrency
Unresolved research. This topic is evidence that research-topic gathered, waiting on resolve-research. It isn't an opinion, and it can cite unvetted material. Follow the opinions instead.
Use async for I/O-bound concurrency only, run it on Tokio, and hold every task to these rules:
- Keep domain logic synchronous, and confine async to I/O and the services you call.
- Never block a runtime thread. Yield to the runtime at least every 10 to 100 µs. An
.awaityields only when its future is pending. Tokio's own channels, sockets, and timers return pending once a task spends its budget, but an always-ready future from elsewhere never does. Send blocking I/O tospawn_blocking, CPU-bound work to rayon, and a loop that runs forever to its own thread. - Give every spawned task an owner. Use a
JoinSetfor tasks whose results you collect, and aTaskTrackerwith aCancellationTokenfor tasks that must finish before shutdown, an actor included.JoinSetstill needs a roster source to support it. For details, see the source gap. Never drop aJoinHandleto detach a task that no owner tracks. - Treat every
.awaitas a cancellation point. In aselect!loop, use only cancel-safe futures, or pin the future outside the loop and poll&mut fut. Spawn a cancel-unsafe operation on theTaskTracker, not on aJoinSetthat its caller owns, so it keeps running when its caller is cancelled. It still stops at the shutdown deadline, so size that for everything the tasks still have to finish. - Hold no lock across an
.await. Guard short critical sections withstd::sync::Mutex, and give a shared I/O resource to one task behind a bounded channel instead of atokio::sync::Mutex. - Bound every channel and queue.
Every API recommended here is stable on Rust 1.99.1, checked with tokio 1.53.3 and 1.54.1 and tokio-util 0.7.20. No recommended crate has an open security advisory at the version named, as Versions records. Async closures (1.85) are the newest async language feature. Everything in Coming next is unstable on nightly as of 2026-10-19.
No opinion file covers this. opinions/rust.md mentions async only in its features table (async closures) and its Coming next list (async fn in dyn traits). This is the async.md topic in PLAN.md: Phase 6.
Whether to use async, and which runtime
Async for concurrency, threads for parallelism. The Book's guidance: CPU-bound, "very parallelizable" work suits threads, and I/O-bound, "very concurrent" work suits async. It adds that "in many cases, the choice isn't threads or async but rather threads and async" (The Rust Programming Language: Futures, Tasks, and Threads, read 2026-10-19). The chapter runs its examples on the Book's own trpl crate, so it teaches the model, not a runtime.
Async only where you need it. corrode: "use async Rust only when you really need it", and "In binary crates, think twice if you really need to use async. It's probably easier to just spawn a thread and get away with blocking I/O." It adds: isolate async code so domain logic stays synchronous, and "In your public library code, avoid async-only interfaces" (Matthias Endler: The State of Async Rust: Runtimes, 2024-02-21, updated 2026-07-30).
Tokio. The same post: "Tokio stands as Rust's canonical async runtime", and "for now, Tokio stands out as the pragmatic choice for real-world implementations". corrode's conflict covers adopting Rust, not a runtime, so it can support this. tokio-blog can't: its notes forbid citing it on adopting Tokio. What rules out the alternatives:
async-stdis discontinued. Its README says "async-stdhas been discontinued; usesmolinstead", and the repository's last push was 2025-08-15 (async-rs/async-std, a reference).smolis "A small async runtime, which is easy to understand" (corrode, above), but has a fraction of Tokio's ecosystem. Embedded targets use their own executors, which are outside this topic.
Versions. Tokio's README lists the LTS lines 1.51.x until March 2027 and 1.53.x until September 2027, both with an MSRV of 1.71 (tokio-rs/tokio: README, a reference, read 2026-10-19). No roster source recommends pinning to an LTS line, so the opinion should state the versions it was checked against and leave the pinning policy out. Releases: tokio 1.53.3 on 2026-10-13, then 1.54.1 on 2026-10-21 (crates.io, read 2026-10-26), and tokio-util 0.7.20 on 2026-10-09, with an MSRV of 1.85 (crates.io).
Advisories. No recommended crate has an open advisory at the version named: tokio 1.53.3 and 1.54.1, tokio-util 0.7.20, trait-variant 0.1.3, async-trait 0.1.92, futures 0.3.34, and rayon 1.12.0. The editor checked each against the RustSec Advisory Database at commit 5fe96cf on 2026-11-12. Two tokio advisories end at these versions. 1.53.3 patches RUSTSEC-2026-0386, unsound AsyncFd constructors in 1.53.0 to 1.53.2. 1.54.1 patches RUSTSEC-2026-0384, a race in tokio::time::Interval in 1.54.0.
Blocking
alice-ryhl, a Tokio maintainer, gives the rule: "Async code should never spend a long time without reaching an .await", and "a good rule of thumb is no more than 10 to 100 microseconds between each .await. That said, this depends on the kind of application you are writing" (Alice Ryhl: Async: What is blocking?, 2020-12-21).
An .await gives the thread back only when its future returns Poll::Pending. A future that's already ready continues in the same poll ([expr.await.effects] in The Rust Reference: Await expressions), so a loop over futures that are always ready can block as surely as a loop with no .await. Tokio narrows the risk with a per-task budget: "Each Tokio resource (socket, timer, channel, ...) is aware of this budget", and once the task is out of budget, they all return not ready until it yields to the scheduler (Tokio: Reducing tail latencies with automatic cooperative task yielding, tokio-blog, 2020-04-01, checked 2026-10-26 against tokio::task::coop for tokio 1.54.1, where poll_proceed "returns Poll::Pending if the budget is depleted").
A loop that awaits a Tokio channel or socket therefore yields without extra code. The loops to check await something outside Tokio that's always ready, such as std::future::ready or a cache hit. The rule measures time between yields, not between .await keywords.
alice-ryhl's summary becomes this table. The Tokio docs' caveats are references: they corroborate the post's rows and add no rule.
| Work | Use | Why |
|---|---|---|
| Blocking I/O: files, a synchronous SDK | tokio::task::spawn_blocking |
A pool with "an upper limit of around 500 threads" (alice-ryhl). A started task "cannot be aborted", and runtime shutdown waits for it (spawn_blocking, a reference) |
| CPU-bound computation | rayon, and a oneshot back |
spawn_blocking is "poorly suited for expensive CPU-bound computations" (alice-ryhl). The same page, a reference, agrees: "Specialized CPU-bound executors, such as rayon, may also be a good fit" |
| A loop that runs forever | std::thread::spawn |
"If a blocking operation keeps running forever, you should run it on a dedicated thread" (alice-ryhl) |
A short std::sync::Mutex critical section |
Nothing | Not blocking in practice. See Shared state |
No roster source covers block_in_place. Its docs say it panics on a current_thread runtime, and suspends any other future the same task is running, such as a join! sibling (block_in_place, a reference). A reference can't support a rule alone, so the opinion should leave it out until a roster source covers it. To call async code from a synchronous program, build a Runtime and call block_on, as the Tokio topic page on bridging with sync code shows (tokio-blog, checked 2026-10-26 against Runtime::block_on for tokio 1.54.1).
Tasks and structured concurrency
The principle. yoshua-wuyts defines structured concurrency as a program whose structure "is guaranteed to be a tree regardless of how much concurrency is going on internally", which gives three properties: cancellation propagates to children, errors propagate to the caller, and "When a function returns, you know it is done doing work". A task with no parent is "a dangling task" (Yoshua Wuyts: Tree-Structured Concurrency, 2023-07-01). Tokio's spawn isn't structured: "A JoinHandle detaches the associated task when it is dropped" (JoinHandle, a reference).
What gives a task an owner on stable Tokio:
| Owner | When | On drop |
|---|---|---|
tokio::join!, try_join! |
A fixed set of futures in one task, which can borrow | Every branch is cancelled with the parent |
tokio::task::JoinSet |
A dynamic set of tasks whose outputs you collect | "all tasks in the JoinSet are immediately aborted" (JoinSet) |
tokio_util::task::TaskTracker with a CancellationToken |
Tasks that must finish, such as request handlers, before shutdown completes | "dropping a TaskTracker does not abort the tasks" (TaskTracker). wait returns once it's closed and empty |
Graceful shutdown has three parts in the Tokio guide: detect the signal, usually with tokio::signal::ctrl_c, tell tasks with a CancellationToken, and wait with a TaskTracker, calling close and then wait (Tokio: Graceful Shutdown, tokio-blog, which names no version, checked against the docs.rs pages for tokio-util 0.7.20). A child token from child_token is cancelled with its parent, and run_until_cancelled returns None once the token is cancelled (CancellationToken, a reference).
close "does not prevent you from spawning new tasks", and wait returns once the tracker is closed and empty (TaskTracker, a reference). A task spawned after wait returns isn't waited for. So if a task that isn't on the tracker spawns onto it, such as an accept loop, stop that task before you call wait. That reading is the editor's.
Source gap: JoinSet. yoshua-wuyts supports the rule that every task has an owner, and corrode supports Tokio. Naming JoinSet as that owner rests on its docs alone, a reference, so it's unsupported. No post on alice-ryhl's blog names JoinSet, TaskTracker, CancellationToken, or tokio-util (checked 2026-11-12).
TaskTracker and CancellationToken are supported. tokio-blog's usage limit lets the guide support using them once another roster source supports adopting Tokio, which corrode does, because they're built in the tokio-rs/tokio repository and only extend Tokio's task API (awesome-humans/rust#100, merged 2026-11-14). The rest of tokio-util keeps the limit. sunshowers lists "Cooperative cancellation: cancellation tokens" as a pattern, which supports the token idea too.
A Tokio-only form needs no crate beyond Tokio, which corrode supports: a JoinSet that the shutdown code drains with join_next, and a tokio::sync::watch channel as the token. That design is the editor's, and the second example below shows it. It also rests on JoinSet, so the opinion uses the first example, and keeps this form out unless a roster source supports JoinSet. It has one limit. JoinSet::spawn takes &mut self, so only the task that owns the set can add to it, while a TaskTracker clones into every handler. A handler that starts a cancel-unsafe operation has to send it to the owning task over a bounded channel.
// Cargo.toml: tokio 1.53.3 with "macros", "rt-multi-thread", "signal", "sync", "time";
// tokio-util 0.7.20 with "rt".
use std::path::PathBuf;
use std::time::Duration;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;
#[tokio::main]
async fn main() {
let token = CancellationToken::new();
let tracker = TaskTracker::new();
let (tx, mut rx) = mpsc::channel::<PathBuf>(64);
tracker.spawn({
let token = token.clone();
async move {
while let Some(Some(path)) = token.run_until_cancelled(rx.recv()).await {
report(path).await;
}
// Cancelled, or every sender dropped: refuse new messages, then drain the queue.
rx.close();
while let Some(path) = rx.recv().await {
report(path).await;
}
}
});
for path in ["Cargo.toml", "src/main.rs"] {
if tx.send(PathBuf::from(path)).await.is_err() {
break;
}
}
tokio::signal::ctrl_c()
.await
.expect("can listen for Ctrl-C");
token.cancel();
tracker.close();
if tokio::time::timeout(Duration::from_secs(10), tracker.wait())
.await
.is_err()
{
eprintln!("tasks still running after 10 s");
}
}
async fn report(path: PathBuf) {
let len = tokio::task::spawn_blocking(move || std::fs::metadata(path).map(|m| m.len()))
.await
.expect("the closure doesn't panic");
match len {
Ok(len) => println!("{len} bytes"),
Err(err) => eprintln!("{err}"),
}
}
On 2026-11-12, the editor compiled this on 1.99.1 with tokio 1.53.3 and 1.54.1 and tokio-util 0.7.20. It passes cargo clippy -- -D warnings with clippy::pedantic on, and cargo fmt --check with templates/rustfmt.toml. The blocking std::fs call goes to spawn_blocking, as the table above says.
Cancellation loses no queued message. rx.recv() is cancel-safe, so cancelling it mid-wait loses no message. After cancellation, close refuses new sends and the second loop handles what the queue still holds (Receiver::close, a reference).
The deadline bounds "runs to completion". If wait takes longer than the 10 s, main returns and the runtime drops. Its tasks then "keep running until they yield. Then they are dropped", and "are not guaranteed to run to completion" (Runtime, a reference, read 2026-11-12 for tokio 1.54.1). A tracked task therefore finishes only inside the deadline. Messages still queued at that point are dropped with the actor.
Size the deadline for the whole drain, not for one operation. With a queue of 64 and a report that takes up to 100 ms, the drain can take 6.5 s: the message in progress plus 64 queued. If you can't bound the drain, treat the deadline as the point where the program discards the remaining work, and log it. That reading is the editor's.
The timeout bounds only wait, not the process. Blocking functions "keep running until they return", and the runtime's Drop "waits forever for this" (the same page). So the program exits only after report's spawn_blocking call returns. Runtime::shutdown_timeout is the method that stops waiting, and it needs a runtime built by hand instead of #[tokio::main].
The Tokio-only form changes the owner and the token. This is a fragment: the channel, the send loop, and report stay as above, and the imports become tokio::sync::{mpsc, watch} and tokio::task::JoinSet.
let (shutdown, _) = watch::channel(());
let mut tasks = JoinSet::new();
tasks.spawn({
let mut shutdown = shutdown.subscribe();
async move {
loop {
tokio::select! {
_ = shutdown.changed() => break,
message = rx.recv() => match message {
Some(path) => report(path).await,
None => break,
},
}
}
rx.close();
while let Some(path) = rx.recv().await {
report(path).await;
}
}
});
// After Ctrl-C:
shutdown.send_replace(());
let drain = async { while tasks.join_next().await.is_some() {} };
if tokio::time::timeout(Duration::from_secs(10), drain)
.await
.is_err()
{
eprintln!("tasks still running after 10 s");
}
The editor compiled the whole program with the same checks on 2026-11-12. changed and recv are both cancel-safe, and main owns the JoinSet until it's drained, so nothing drops it while a task runs.
Actors for owned state. alice-ryhl's actor pattern gives state to one task and talks to it through a cloneable handle. The post says to "use a bounded channel so that the number of messages waiting in the channel don't grow without bound". When all senders drop, recv returns None and the actor shuts down. Avoid a cycle made only of bounded channels, which can deadlock (Alice Ryhl: Actors with Tokio, 2021-02-13). The post starts the actor with tokio::spawn and drops the JoinHandle. Under the ownership rule, spawn it on the TaskTracker instead, so shutdown waits while the actor drains its queue, as the example does. That reconciliation is the editor's.
Cancellation
Two properties. sunshowers separates them: "cancel safety is a local property of an individual future", the ability to be dropped without side effects, while cancel correctness is a property of the whole system. A bug needs a cancel-unsafe future that is actually cancelled and a system property that breaks. Select loops "are particularly prone to cancel correctness issues", but select! isn't the only source: try_join! cancels its siblings when one fails, and let _ = fut; drops a future without polling it (Rain: Cancelling async Rust, 2025-10-03, corrected 2025-10-24).
The post's mitigations. An opinion can apply each as a rule:
- Avoid Tokio mutexes. A guard held across an
.awaitusually leaves an invariant broken when the future is dropped. - Make APIs cancel-safe. Reserve a channel slot with
reservebefore building the message, and write withwrite_all_bufand a cursor, notwrite_all. - Drive cancel-unsafe futures to completion. At Oxide, "a task for each HTTP request" fixed a cancellation bug, because dropping a
JoinHandledoesn't cancel the task. Spawn it on theTaskTracker, which doesn't abort on drop. AJoinSetthat the caller owns doesn't work here: it drops with the caller, which aborts every task in it. A tracked task still stops at the shutdown deadline. - Pin a future outside a
select!loop, and poll&mut fut, so a cancelled branch keeps its place. For how this can deadlock, and the conditions that avoid it, see the unvetted futurelock RFD under Watch-list and unvetted material.
Which Tokio futures are cancel-safe comes from the select! docs. JoinSet::join_next is from the JoinSet docs: "This method is cancel safe". &mut JoinHandle is from the JoinHandle docs: "Awaiting a &mut JoinHandle<T> is cancel safe". All three are references, and which future is cancel-safe is a reference fact about Tokio's own API, so each entry rests on its docs (checked 2026-11-14 against the docs for tokio 1.54.1). sunshowers also supports two entries, write_all and Mutex::lock. The rule to use only cancel-safe futures in a select! loop is a choice, and sunshowers supports it:
| Cancel-safe | Not cancel-safe |
|---|---|
mpsc::Receiver::recv, broadcast::Receiver::recv, watch::Receiver::changed, TcpListener::accept, AsyncReadExt::read, AsyncWriteExt::write, StreamExt::next, JoinSet::join_next, &mut JoinHandle |
read_exact, read_to_end, read_to_string, and write_all lose data. Mutex::lock, RwLock::read and write, Semaphore::acquire, and Notify::notified lose their place in the queue |
select! picks a branch at random by default, for fairness, and a loop marked biased; polls top to bottom (the select! docs). The editor reads that as "put the shutdown branch first under biased;, where a stream that's always ready can't starve it", but no roster source says so, and the opinion should leave it out until one does. tokio::time::timeout cancels its future by dropping it, and the same rules apply.
Shared state
The Tokio docs answer the mutex question: "Contrary to popular belief, it is ok and often preferred to use the ordinary Mutex from the standard library in asynchronous code." The async mutex's only advantage is being held across an .await, and for a shared I/O resource "it is often better to spawn a task to manage the IO resource, and to use message passing" (tokio::sync::Mutex, a reference). The tutorial says the same, and warns that a MutexGuard from a crate that implements Send for it compiles across an .await and deadlocks (Tokio: Shared state, tokio-blog).
No docs.rs page restates the deadlock (checked 2026-10-26 for tokio 1.54.1), but it depends on no Tokio version. A Send guard doesn't stop the future being Send, so tokio::spawn accepts it when nothing else held across the .await breaks that bound. Clippy's await_holding_lock catches the case for std and parking_lot guards.
sunshowers and alice-ryhl both point to the actor pattern instead. Wrap the Arc<Mutex<T>> in a type with synchronous methods, so no caller can hold the guard across an .await.
Channels. "Unbounded queues will eventually fill up all available memory and cause the system to fail in unpredictable ways" (Tokio: Channels, tokio-blog, checked 2026-10-26 against tokio::sync::mpsc for tokio 1.54.1, whose unbounded channel works "without backpressure"). Use mpsc::channel(capacity), oneshot for a reply, broadcast for fan-out, and watch for the latest value. recv on std::sync::mpsc or crossbeam blocks the thread until a message arrives, so alice-ryhl's blocking rule forbids it on a runtime thread. The mpsc docs agree: "use the kind of channel that matches where the receiver is".
Lints
Clippy enforces several of the rules above: lock and borrow guards held across an .await, futures dropped without being polled, and future size. Task ownership, bounded queues, and where blocking work runs have no lint. Groups, levels, and versions are from Clippy Lints, 1.99, read 2026-10-19, and the editor confirmed each level with a probe on 1.99.1.
| Lint | Group | Level | Added | Catches |
|---|---|---|---|---|
async_yields_async |
correctness | deny | 1.48 | An async block whose output is itself a future that was never awaited |
await_holding_lock |
suspicious | warn | 1.45 | A std::sync or parking_lot MutexGuard held across an .await |
await_holding_refcell_ref |
suspicious | warn | 1.49 | A RefCell borrow held across an .await |
await_holding_invalid_type |
suspicious | warn | 1.62 | The types listed in await-holding-invalid-types in clippy.toml, such as a project's own guard |
let_underscore_future |
suspicious | warn | 1.67 | let _ = fut;, which drops a future without polling it |
manual_async_fn |
style | warn | 1.45 | fn f() -> impl Future { async { … } } that could be an async fn |
redundant_async_block |
complexity | warn | 1.70 | async { fut.await } |
large_futures |
pedantic | allow | 1.70 | A future over future-size-threshold, 16384 bytes by default. The fix is Box::pin |
unused_async |
pedantic | allow | 1.54 | An async fn with no .await |
future_not_send |
nursery | allow | 1.44 | An async fn whose future isn't Send, for a library that must run on a multi-threaded runtime |
Rustc adds async_fn_in_trait (warn), covered below. A workspace that warns on clippy::pedantic gets large_futures and unused_async with the group. Future size matters beyond the stack: tweede-golf measured duplicated states in the compiler's async state machines, and on stable the fix is to write each .await once, hoisting a shared call out of the match arms (Tweede golf: Async Rust never left the MVP state, 2026-05-04). Its compiler changes are a 2026 project goal, not stable Rust.
Async in traits and closures
Each row is the first stable release, from rust-blog and the release notes.
| Feature | Release | Use |
|---|---|---|
IntoFuture |
1.64 | .await on a builder without a send() call |
std::pin::pin! |
1.68 | Pin a future on the stack for a select! loop, instead of Box::pin or tokio::pin! |
async fn and RPITIT in traits |
1.75 | Replace #[async_trait] for static dispatch. In a public trait, rustc's async_fn_in_trait lint warns because callers can't require Send. Use #[trait_variant::make(SendName: Send)] for a Send twin of the local trait, or write fn f(&self) -> impl Future<Output = T> + Send |
Recursive async fn behind indirection |
1.77 | Box::pin(recurse()).await, with no helper crate |
Async closures and AsyncFn* bounds |
1.85 | async \|x\| … and F: AsyncFn(T) -> U, which can borrow from their arguments, over \|\| async move { … } and Fn() -> impl Future |
The trait guidance is from Rust Blog: Announcing async fn and return-position impl Trait in traits (2023-12-21): "We recommend using the trait_variant::make proc macro to let your users choose", and these traits "are not object-safe". trait-variant is at 0.1.3, from the rust-lang organisation. A trait that needs dyn still uses async-trait (0.1.92), until the async fn in dyn traits row in Coming next reaches stable. Releases 1.86 to 1.99 brought no new async feature, only Pin soundness fixes (1.92, 1.96, 1.97, and 1.99 in RELEASES.md).
Where the sources disagree
- Spawning versus in-task concurrency.
yoshua-wuytsargues that tasks are "a poor fit for non-parallel concurrent execution", and prefers joining futures in one task (Yoshua Wuyts: Tasks are the wrong abstraction, 2024-04-27).sunshowersspawns tasks because a task survives its caller's cancellation. They agree once read as: join futures inside a task when they belong to it, and spawn a task on aTaskTrackerwhen it must outlive a cancellation. AJoinSetthat the caller owns can't do this, because dropping it aborts its tasks. That reading is the editor's.yoshua-wuytsmaintainsfutures-concurrency, and its notes forbid citing it alone on adopting that crate, so the opinion should recommendtokio::join!andJoinSet, not the crate. - CPU-bound work in a task. Watch-list
ms-rust-guidelinessays a long computation "should containyield_now().awaitpoints" (M-YIELD-POINTS).alice-ryhland the Tokio docs move the work off the runtime instead. Followalice-ryhland the Tokio docs:alice-ryhlis citable and a maintainer, andms-rust-guidelinesis watch-list. Yielding keeps the work on a worker thread, where it still competes with I/O.
Coming next
Unstable on nightly as of 2026-10-19, not yet an opinion. Statuses are from the tracking issues and Rust Project Goals: 2026, which are references.
| Feature | Status, 2026-10-19 |
|---|---|
async fn in dyn traits |
Experimental (rust-lang/ |
| Return type notation | RFC approved, implementation incomplete (rust-lang/impl Trait in type aliases. It's what lets a caller write T::f(..): Send |
| Async drop | Unstable codegen (rust-lang/ |
AsyncIterator |
Unstable (rust-lang/futures::Stream (0.3.34) and StreamExt meanwhile |
Pin ergonomics (&pin mut) |
Experimental. The 2026 goals list "Continue Experimentation with Pin Ergonomics". The &pin type syntax has parsed since 1.84 |
| Async state machine size | Two 2026 goals, one led by the tweede-golf post's author. Compiler work, with no new syntax |
Return type notation is the row that changes the trait guidance: once stable, a public trait can use bare async fn, and callers add Send where they need it.
Watch-list and unvetted material
Kept apart from the roster findings above. None of it supported a claim.
- Watch-list
ms-rust-guidelines: M-ASYNC-FN prefersasync fnto aFuture-returning signature, and M-ASYNC-STACK-SIZE asks hotasync fns to track their future sizes (Microsoft: Pragmatic Rust Guidelines). Both agree withmanual_async_fnandlarge_futures. M-YIELD-POINTS is the disagreement above. - Watch-list
without-boats: "FuturesUnordered and the order of futures" (2024-02-18) and "Asynchronous clean-up" (2024-02-24) explain intra-task concurrency and why async drop is hard. Both are design history, with no practice that the roster lacks. - Unvetted: Oxide RFD 609: Futurelock (David Pacheco, undated on the page). It defines futurelock as a deadlock where one future holds a resource, such as a fair Tokio mutex's turn, that another needs, while the task has stopped polling the first. Triggers: a
&mut futbranch inselect!beside an.awaitin another branch, and aFuturesUnorderedloop that awaits something else. Mitigation: "be extremely careful that the task never stops polling a future that it previously started polling", most simply by spawning the future and selecting on itsJoinHandle. For aFuturesOrderedorFuturesUnordered, it says to "consider instead using tokio'sJoinSet". It adds a condition tosunshowers' mitigation 4: pinning outside the loop keeps the place, but the pinned future must be polled again.
What this means for the repository
- No opinion covers the topic. Run
resolve-researchto createopinions/async.md. Its first sentence is the opening list here. It needs these sections: whether to use async and which runtime, blocking, task ownership and graceful shutdown with the example, cancellation with the cancel-safety entries, shared state and channels, the lint table, and traits and closures. List it under README.md's Scope and in the layout tree. - Leave out what no roster source supports. These rest only on references or on the editor's reading: pinning to a Tokio LTS line, avoiding
block_in_place, putting the shutdown branch first underbiased;, the shutdown deadline rule, and the futurelock RFD's conditions on a pinned future. The cancel-safety entries are reference facts, so the opinion can list them all, citing the Tokio docs. Promote them only ifresolve-researchfinds a roster source. JoinSetstill needs a roster source. Since awesome-humans/rust#100 merged, the Tokio guide supportsTaskTrackerandCancellationTokenfor tasks that must finish before shutdown, so the opinion uses the first example under Tasks and structured concurrency. For tasks whose results you collect, the opinion namesJoinSetonly ifresolve-researchfinds a roster source for it. Otherwise it states that part of the ownership rule without naming a type.opinions/rust.mdcan link it. Its features-table row on async closures and its Coming next item onasync fnindyntraits should point toasync.mdonce that exists, and the Coming next item can move there.- No template change.
large_futuresandunused_asynccome withclippy::pedantic, whichtemplates/Cargo.tomldoesn't turn on, andawait-holding-invalid-typesneeds a project's own types. A futureclippy.tomltemplate is the place for it, if one is added. - Gaps in this scan. The workers that were to read
niko-matsakis's async posts andfasterthanlime's async articles stopped on a usage limit, and the editor didn't cover them. Neither source was expected to support a claim:niko-matsakiswrites proposals, which could only add to Coming next.resolve-researchshould check both before relying on that list. vet-sourcecandidate: Oxide RFDs (rfd.shared.oxide.computer), for RFD 609 and the RFDs 397 and 400 thatsunshowersrecommends on cancellation. They're engineering design documents from a company that ships Rust in production. The vetting has to check their longevity and independence.