In the previous post , a Future runs when you .await it—and that wait blocks the current task until that future completes.
If every async operation had to finish before the next one started, you’d be back to serial code. Here we look at Tokio patterns for real concurrency across multiple futures.
join When you want every branch to finish before you continue, run them together and wait for all results. join! does that:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 async fn async_fn1 () -> u32 { 1 } async fn async_fn2 () -> u32 { 2 } #[tokio::main] async fn main () { let (first, second) = tokio::join!(async_fn1 (), async_fn2 ()); assert_eq! (first, 1 ); assert_eq! (second, 2 ); }
try_join Branches can return Err. try_join! short-circuits on the first error instead of waiting for the rest:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 async fn async_fn1 () -> Result <u32 , &'static str > { Ok (1 ) } async fn async_fn2 () -> Result <u32 , &'static str > { Err ("async_fn2 failed" ) } #[tokio::main] async fn main () { let res = tokio::try_join!(async_fn1 (), async_fn2 ()); match res { Ok ((first, second)) => { println! ("first = {}, second = {}" , first, second); } Err (err) => { println! ("error: {}" , err); } } }
spawn join! overlaps futures but still runs them on the same task . To give each piece of work its own task, use spawn.
A spawned task starts immediately in the background—even if you never .await its JoinHandle.
It’s like thread spawn, but the unit is a task , not an OS thread.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 use futures::future::join_all;use tokio::{join, task::JoinHandle};async fn async_op (id: i32 ) -> String { let s = format! ("Start task {}" , id); println! ("{}" , s); s } #[tokio::main] async fn main () { let ops = vec! [1 , 2 , 3 ]; let mut tasks : Vec <JoinHandle<String >> = ops .into_iter () .map (|op| tokio::spawn (async_op (op))) .collect (); let outputs = join_all (tasks).await ; println! ("{:?}" , outputs); }
select When the first completing branch should win and the others should be dropped (releasing their futures), use select!:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 async fn async_fn1 () {}async fn async_fn2 () {}#[tokio::main] async fn main () { tokio::select! { _ = async_fn1 () => { println! ("async_fn1() completed first" ) } _ = async_fn2 () => { println! ("async_fn2() completed first" ) } }; }
Ordered polling select! does not guarantee branch order—it may poll branches in arbitrary order. For deterministic priority, use biased:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 #[tokio::main] async fn main () { let mut count = 0u8 ; loop { tokio::select! { biased; _ = async {}, if count < 1 => { count += 1 ; assert_eq! (count, 1 ); } _ = async {}, if count < 2 => { count += 1 ; assert_eq! (count, 2 ); } else => { break ; } }; } }
Preconditions Branches can use if precondition. When the loop reaches a branch, a true condition runs it; a false one marks the branch disabled for that select! round.
On the next loop iteration, disabled flags reset.
If every branch is disabled, you need an else branch—or Tokio panics: all branches are disabled and there is no else branch.
Rewriting branches You can swap what a pinned branch points at—for example with Pin::set:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 use tokio::select;async fn action (input: Option <i32 >) -> Option <String > { match input { Some (input) => Some (input.to_string ()), None => return None , } } #[tokio::main] async fn main () { let (tx, mut rx) = tokio::sync::mpsc::channel (128 ); let mut done = false ; let operation = action (None ); tokio::pin!(operation); tokio::spawn (async move { let _ = tx.send (1 ).await ; let _ = tx.send (3 ).await ; let _ = tx.send (2 ).await ; }); loop { select! { res = &mut operation, if !done => { println! ("Got = {:?}" , res); done = true ; if let Some (_) = res { return ; } } Some (v) = rx.recv () => { if v % 2 == 0 { operation.set (action (Some (v))); done = false ; } } } } }
The if !done guard matters: without it you might poll an already-finished future and hit async fn resumed after completion.
Cancellation When one select! branch completes, the others are cancelled via Drop—the runtime stops polling those futures.
For example, when a oneshot::Receiver is dropped on cancel, the sender sees closed() so it can clean up:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 use tokio::sync::oneshot;#[tokio::main] async fn main () { let (mut tx1, rx1) = oneshot::channel::<u32 >(); let (tx2, rx2) = oneshot::channel (); tokio::spawn (async move { tokio::select! { _ = tx1.closed () => { println! ("tx1 closed" ); } } }); tokio::spawn (async { let _ = tx2.send ("two" ); }); tokio::select! { val = rx1 => { println! ("rx1 completed first with {:?}" , val); } val = rx2 => { println! ("rx2 completed first with {:?}" , val); } } }