Rust Async Await: Futures, Pinning, and Tokio Task Execution
An async fn runs nothing until an executor polls it. Await points, Send bounds, blocking in a worker, cancellation and the runtime nesting panic.

Quick Summary
An async fn does not run anything when called. It returns a Future — a state machine that does nothing until something polls it. The executor (usually Tokio) drives that polling loop on a small pool of OS threads, and .await yields control back to the executor whenever the future is not ready. That is why a thousand concurrent connections cost a thousand small state machines rather than a thousand threads.
Three facts explain most async bugs. Nothing runs without an executor: main must be #[tokio::main] or the future must be handed to a runtime. A blocked worker blocks every task on it: synchronous I/O or a long computation inside an async task stalls the whole thread, so blocking work belongs in spawn_blocking or a dedicated thread. Cancellation is dropping the future: a task aborted or a future dropped mid-await stops at that point, which is why cancellation safety matters for select! arms.
tokio::spawn needs Send + 'static, so references to locals cannot cross a spawn and shared state needs Arc. The compiler's "future cannot be sent between threads safely" message almost always points at a non-Send value — a std::sync::MutexGuard or an Rc — held across an .await.
Basic syntax and query signatures
use std::time::Duration;
use tokio::time::{sleep, timeout};
#[tokio::main] // builds a multi-thread runtime
async fn main() -> anyhow::Result<()> {
// Sequential await: one after the other
let a = fetch("a").await?;
let b = fetch("b").await?;
// Concurrent: both futures polled on the same task
let (a, b) = tokio::join!(fetch("a"), fetch("b"));
// Fallible concurrency: first error wins
let (a, b) = tokio::try_join!(fetch("a"), fetch("b"))?;
// Spawned task: independent, needs Send + 'static
let handle = tokio::spawn(async move { work().await });
let out = handle.await?; // JoinError if the task panicked
// Timeout and sleep
let v = timeout(Duration::from_secs(2), fetch("slow")).await??;
sleep(Duration::from_millis(50)).await;
println!("{a} {b} {out} {v}");
Ok(())
}
async fn fetch(key: &str) -> Result<String, std::io::Error> {
Ok(format!("value of {key}"))
}
async fn work() -> u32 { 42 }Concurrency primitives that belong to async code, not std:
use tokio::sync::{mpsc, oneshot, Mutex, Semaphore};
// Channel: bounded, async-aware (capacity required)
let (tx, mut rx) = mpsc::channel::<Job>(100);
tokio::spawn(async move {
while let Some(job) = rx.recv().await {
process(job).await;
}
});
tx.send(Job::new()).await?; // .await, unlike std's blocking send
// One-shot response channel
let (resp_tx, resp_rx) = oneshot::channel();
tokio::spawn(async move { let _ = resp_tx.send(7u8); });
let n = resp_rx.await?;
// Async mutex: held across .await legally
let shared = std::sync::Arc::new(Mutex::new(0u64));
{
let mut g = shared.lock().await; // tokio::sync::Mutex
*g += 1;
} // guard dropped before the next await
// Bound concurrency
let sem = std::sync::Arc::new(Semaphore::new(10));
let permit = sem.clone().acquire_owned().await?;
drop(permit);Key comparison table
| Situation | Use | Why |
|---|---|---|
| Network / timer I/O | async + tokio | Suspends instead of blocking a thread |
| CPU-heavy work | spawn_blocking or a thread | Would stall the runtime worker |
| File I/O in async code | tokio::fs or spawn_blocking | std::fs blocks the worker |
| Short critical section, no await | std::sync::Mutex | Cheaper than the async mutex |
Lock held across .await | tokio::sync::Mutex | Compiles and behaves correctly |
| Many readers, shared state | Arc<RwLock<T>> (tokio or std) | Read concurrency |
| Fan-in from many tasks | tokio::sync::mpsc | Async-aware backpressure |
| Request/response between tasks | oneshot | One value, one receiver |
| Runtime | Model | Spawn signature |
|---|---|---|
Tokio (#[tokio::main]) | Multi-thread work stealing (default) | Send + 'static |
Tokio (current_thread) | Single-threaded | 'static (no Send needed) |
| async-std | Multi-threaded pool | Send + 'static |
futures::executor::block_on | Minimal, one future | None |
| Error / message | Cause | Fix |
|---|---|---|
future cannot be sent between threads safely | Non-Send value held across .await | Scope it, or use a Send type |
future cannot be shared between threads safely | & across threads needs Sync | Clone the value out |
cannot start a runtime from within a runtime | block_on inside async | Use .await |
task panicked on JoinError | Spawned task panicked | Handle the error, or use catch_unwind |
Elapsed from timeout | Future took too long | Retry or fail explicitly |
Deadlock with std::sync::Mutex | Guard held across .await | tokio::sync::Mutex or drop the guard |
Practical edge cases and deep dives
1. A std::sync::MutexGuard across .await does not compile — on purpose
let shared = Arc::new(std::sync::Mutex::new(String::new()));
// error[E0277]: future cannot be sent between threads safely
// tokio::spawn(async move {
// let mut g = shared.lock().unwrap();
// some_io().await;
// g.push('x');
// });MutexGuard is !Send, so a task holding one cannot be moved between worker threads. Three valid fixes:
// A: scope the guard so it is dropped before the await
tokio::spawn(async move {
let snapshot = { let g = shared.lock().unwrap(); g.clone() };
some_io().await;
let _ = snapshot;
});
// B: use the async mutex
let shared = Arc::new(tokio::sync::Mutex::new(String::new()));
tokio::spawn(async move {
let mut g = shared.lock().await;
some_io().await;
g.push('x');
});
// C: do the mutation as one short operation
tokio::spawn(async move {
some_io().await;
shared.lock().unwrap().push('x');
});Option B is the one that keeps the lock across the await, which is usually what the code actually wanted.
2. Blocking inside a task stalls unrelated tasks
// Bad: blocks one of the runtime's worker threads
tokio::spawn(async move {
let text = std::fs::read_to_string("big.csv").unwrap();
});
// Good: offload to the blocking pool
tokio::spawn(async move {
let text = tokio::task::spawn_blocking(move || std::fs::read_to_string("big.csv"))
.await
.unwrap()
.unwrap();
});The default Tokio runtime has one worker per CPU core. Four blocked workers on a four-core machine means every timer, every socket, and every spawned task stops until the I/O returns — the classic "it works on my laptop with two requests" failure.
3. select! cancels the losing branches
use tokio::select;
select! {
v = rx.recv() => println!("got {v:?}"),
_ = sleep(Duration::from_secs(1)) => println!("timeout"),
_ = shutdown.recv() => println!("shutdown"),
}When one branch completes, the others are dropped at their current point. mpsc::Receiver::recv is cancellation safe (a message is not lost if the branch is dropped before it completes), but read on a TcpStream partially is not: bytes already consumed are gone. Check each API's cancellation-safety note before putting it in select!; wrap unsafe cases in a task that owns the future.
4. spawn needs 'static, so locals must be cloned or moved
let cfg = Arc::new(load_config());
let mut handles = Vec::new();
for shard in 0..4 {
let cfg = Arc::clone(&cfg);
handles.push(tokio::spawn(async move {
process_shard(&cfg, shard).await
}));
}
for h in handles { h.await?; }Borrowing cfg directly gives E0521 borrowed data escapes outside of method or the 'static requirement error. Cloning an Arc per task is the idiomatic fix.
5. Nested runtimes: block_on inside async panics
// panic: Cannot start a runtime from within a runtime
// async fn handler() {
// let v = tokio::runtime::Runtime::new().unwrap().block_on(async { 1 });
// }If a synchronous library calls block_on internally, call that library from spawn_blocking so the blocking thread has no current runtime. Handle::current().block_on has the same restriction; tokio::task::block_in_place exists but requires the multi-threaded runtime.
6. Concurrency limits without a thread pool
let sem = Arc::new(tokio::sync::Semaphore::new(20));
let mut tasks = Vec::new();
for url in urls {
let sem = Arc::clone(&sem);
tasks.push(tokio::spawn(async move {
let _permit = sem.acquire().await.unwrap();
fetch(url).await
}));
}
for t in tasks { t.await??; }join_all over ten thousand futures opens ten thousand sockets at once; a semaphore caps in-flight work while keeping the code async. futures::stream::iter(...).buffer_unordered(20) does the same for a stream of futures.
7. Pinning: why Box::pin appears in signatures
use std::future::Future;
use std::pin::Pin;
fn boxed<'a>(f: impl Future<Output = u8> + Send + 'a) -> Pin<Box<dyn Future<Output = u8> + Send + 'a>> {
Box::pin(f)
}An async state machine can hold references to its own fields, so moving it after polling would invalidate them. Pin guarantees the future is not moved once polling starts; Box::pin is the usual way to get a pinned heap allocation. Storing futures of different concrete types in one collection requires exactly this. impl Future in return position avoids it entirely when the type is statically known.
Common mistakes and runtime errors
| Error / message | Cause | Fix |
|---|---|---|
E0277 future cannot be sent between threads safely | Non-Send value across .await | Scope it, or use a Send type/tokio::sync |
E0521 borrowed data escapes outside of method | Borrow in spawn | Arc::clone or move owned data |
cannot start a runtime from within a runtime | Nested block_on | .await, or spawn_blocking |
task is not Send`` on tokio::spawn | Rc/RefCell captured | Arc/Mutex |
| Timeouts never fire | Blocking call inside the task | spawn_blocking |
JoinError::Cancelled | Task aborted | Treat as a normal cancellation path |
Deadlock with tokio::sync::Mutex | Two locks, opposite order | Consistent order, or one lock |
Message lost after select! | Non-cancellation-safe branch dropped | Wrap in a task or use a safe API |
| Everything runs sequentially | .await inside a for loop | join_all/FuturesUnordered/spawn |
Elapsed under load | Blocked worker pool | Shorten blocking sections, raise worker_threads |
| Future never completes | Awaiting a future that was never polled or a dropped sender | Check task lifetime and channel closure |
Try matching browser tools
All toolsSmall utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Rust guides
All Rust guidesRust Unsafe: Raw Pointers, FFI Bindings, and Soundness Invariants
What unsafe actually unlocks, the five soundness contracts behind raw pointers, and the FFI rules for repr(C), CString and unwinding.
Rust Pin and Unpin: Memory Pinning, Self-Referential Structs, and Futures
Why a future must not move after polling starts, what Unpin opts out of, and how Box::pin, pin! and map_unchecked_mut express that guarantee.
Rust Arrays and Slices: Fixed Arrays, &[T] Fat Pointers, and DSTs
An array carries its length in its type; a slice carries it in the pointer. The split_at_mut, chunks and TryFrom patterns that follow from that.
Rust Macros: macro_rules! Patterns, Hygiene, and Procedural Macros
Matcher fragments, repetition, hygiene and the proc-macro crate. How to read a macro_rules! error and when a derive macro is the right tool.
More in Rust
All Rust guidesThe guides filed next to this one in Rust, in library order.