In Rust, what changes when you pass two futures to `futures::join!` instead of awaiting them one after the other?
answer
- one task, two branches
- sum of waits vs longest wait
- polled in turn at each .await
- concurrency is not parallelism
basics
~20 sSequential awaits run the futures one after the other, so the waits add up. futures::join! polls both on one task, interleaving them at each .await, so the total is about the longest wait: concurrency, not parallelism.
solid answer
~40 sWith `let a = f1.await; let b = f2.await;` the second future is not even polled until the first finishes, so two 200 ms waits take about 400 ms. `futures::join!(f1, f2)` pins both futures inside the current async block and polls each unfinished one every time the task is woken, so both waits overlap and the call returns a tuple `(a, b)` in argument order after about 200 ms. Both branches still run on one task, which one executor thread polls at a time: this is concurrency, not parallelism. A blocking call such as `std::thread::sleep` or a long CPU loop in one branch therefore stalls the other branch too. Use `join!` when the futures are independent; if `f2` needs `f1`'s output, sequential `.await` is correct.
code
rust · 30 linesuse futures::join;
use smol::Timer;
use std::time::{Duration, Instant};
async fn fetch(id: u32) -> u32 {
Timer::after(Duration::from_millis(200)).await;
id
}
fn main() {
smol::block_on(async {
let t = Instant::now();
let a = fetch(1).await;
let b = fetch(2).await;
println!("sequential: ({a}, {b}) after ~{} ms", t.elapsed().as_millis() / 100 * 100);
let t = Instant::now();
let (a, b) = join!(fetch(1), fetch(2));
println!("join!: ({a}, {b}) after ~{} ms", t.elapsed().as_millis() / 100 * 100);
// A blocking call in one branch stalls every branch of the join!
let t = Instant::now();
let blocking = async {
std::thread::sleep(Duration::from_millis(200));
3
};
let (c, a) = join!(blocking, fetch(1));
println!("blocking: ({c}, {a}) after ~{} ms", t.elapsed().as_millis() / 100 * 100);
});
}go deeper
Recall that two awaits in a row run one after the other, while futures::join! lets both futures make progress and returns a tuple once both are done.
Explain that join! pins its arguments and polls every unfinished one on each wake-up, all inside one task, and why that makes it concurrency rather than parallelism.
Show that you would spot a blocking call or a long CPU loop hidden in one branch, because it silently serialises every other branch of the join.
Frame the choice as overlap of waiting versus parallel work: join! for a few independent I/O waits, tasks or threads when computation must use more cores.
## Two ways to wait for two things In Rust an `async fn` returns a **future**: a value whose type implements `Future` and which does nothing until something polls it. `.await` is how an async body asks for a future's result. Writing two awaits in a row is the simplest way to combine two futures, and the most common accidental bottleneck: ```rust let a = fetch(1).await; // fetch(2) does not exist yet let b = fetch(2).await; ``` The second call does not even create its future until the first one has completed, so the waits **add up**. If each request waits 200 ms on the network, the pair takes about 400 ms. `futures::join!` from the `futures` crate is the concurrent alternative: ```rust let (a, b) = futures::join!(fetch(1), fetch(2)); ``` Both futures exist from the start and both make progress while the other waits, so the pair takes about as long as the **slower** of the two, here about 200 ms. The macro returns a tuple of outputs in the order the arguments were written, once every future has finished. ## What the macro actually does Reading the macro's expansion in futures 0.3 shows a small, predictable mechanism: 1. Each argument is moved into a local, wrapped so it can remember its output once done, and pinned in place. 2. A single future built with `poll_fn` is awaited. Every time it is polled, it polls **each unfinished** future in argument order. 3. If all of them are ready it returns the tuple; otherwise it returns `Poll::Pending`, and any of the inner futures can wake the task later. The consequences that interviewers probe: - **One task.** `join!` creates no tasks and no threads. The enclosing async block is one future, polled by whatever executor drives it. - **Interleaving only at `.await`.** A branch gives up control only when the future it awaits returns `Pending`. Code between two awaits runs without interruption. - **Re-polling.** On every wake-up all unfinished branches are polled, not just the one that was woken. That is fine for a handful of futures; for hundreds, a structure that polls only woken futures (such as `FuturesUnordered`) scales better. - **Async context only.** The macro expands to an `.await`, so it is usable only inside an `async fn`, async block or async closure. - **Not std.** `std::future::join!` exists but is unstable; stable code uses `futures::join!` or a runtime's own equivalent. ## Concurrency, not parallelism | | sequential `.await` | `futures::join!` | futures spawned as tasks on a multi-threaded executor | |---|---|---|---| | futures in progress at once | one | all | all | | threads involved | the polling thread | the polling thread | possibly several | | total time for two 200 ms waits | ~400 ms | ~200 ms | ~200 ms | | CPU-bound work in both | serial | serial | can run in parallel | **Concurrency** means several pieces of work are in progress during the same period; **parallelism** means they are executing at the same instant on different cores. `join!` gives the first and never the second. The demonstration snippet makes the distinction visible: two timer waits overlap, but when one branch calls `std::thread::sleep(200 ms)` before its first `.await`, the thread is stuck inside that branch and the other branch is not polled at all. Its timer is not even created until the sleep returns, so the total is back to about 400 ms. The same applies to a CPU-heavy loop with no `.await` inside it. Waiting on I/O or timers overlaps well under `join!`; computation does not. Getting real parallelism means spawning tasks onto a multi-threaded executor or using threads, which the lessons on spawning and on threads cover. ## When to use which - **Independent futures, small fixed number:** `join!` (or `try_join!` when each returns a `Result` and the first error should end the wait). - **A `Vec` or iterator of futures:** `futures::future::join_all`, which keeps input order. - **Thousands of futures, or results needed as they finish:** a stream such as `FuturesUnordered` or `buffer_unordered`. - **A data dependency:** sequential `.await`. If `b` needs `a`'s output, `b`'s future cannot even be built until `a` has finished, so there is nothing to overlap. The interview answer in one line: `join!` overlaps the waiting, not the work, because every branch still shares one task and one thread at a time.
- If `join!` only overlaps waiting, how do you get two CPU-heavy computations to run in parallel from async code?Move them off the polling thread: spawn them as tasks on a multi-threaded executor, run them on a thread or a thread pool, and await the handles. `join!` alone keeps both branches on one task, so their computation still runs one after the other on whichever thread polls that task.
- Does `futures::join!` poll only the branch that was woken?No. In futures 0.3 the expansion polls every unfinished branch, in argument order, each time the combined future is polled. Finished branches just hold their output. For a few futures this costs nothing; for a large, changing set, `FuturesUnordered` polls only the futures whose wakers fired.
- What does `join!` return, and in what order?A tuple with one element per argument, in the order the arguments were written, regardless of which future finished first. The macro returns only when every future has completed, so nothing is available early; when results should be handled as they arrive, use a stream such as `FuturesUnordered` instead.
One cook watching two pots on one stove: both simmer at once, but if the cook stops to knead dough by hand, neither pot gets stirred until the kneading is done.
- join! runs each future on its own thread
- join! returns the result of whichever future finishes first
- Awaiting two futures in a row already runs them at the same time
- A blocking call inside one join! branch only delays that branch
- join! needs each future to be Send and 'static