Construct a Rust function using tokio::select! to race two async computations and cancel…
- User
Construct a Rust function using
tokio::select!to race two async computations and cancel the loser. Assistant
Construct a Rust function using tokio::select! to race two async computations and cancel the loser.
The user wants a Rust function demonstrating tokio::select!.
The specific requirements are:
Key concepts to cover:
tokio::select! macro syntax.select! automatically cancels the other branches when one matches.tokio::time::sleep).Plan:
race_computations. It needs to be async. It should probably return the result of the winner (e.g., a String or u32). Let's return a String for clarity, indicating which branch won.select! drops the future, standard print statements inside the future won't run after the drop unless the future has a Drop implementation or uses a specific cancellation token pattern (which might be too advanced for a basic example, but good to keep in mind).select! does) is cancellation. I don't need to implement cooperative cancellation (like CancellationToken) unless I want to show how to handle cleanup, but select! implies immediate dropping.select! block:
tokio::select! {
res_a = computation_a() => { ... },
res_b = computation_b() => { ... },
}
main function to drive it.Drafting the code:
use tokio::time::{sleep, Duration};
async fn computation_a() -> String {
sleep(Duration::from_millis(50)).await;
"Computation A finished".to_string()
}
async fn computation_b() -> String {
sleep(Duration::from_millis(100)).await;
"Computation B finished".to_string()
}
async fn race() -> String {
tokio::select! {
// Branch 1
result = computation_a() => {
result
}
// Branch 2
result = computation_b() => {
result
}
}
}
Refining the "cancel" aspect:
The prompt specifically mentions canceling the loser. In tokio::select!, this happens implicitly.
If the user wants to see evidence of cancellation, I should perhaps use a scope or a Drop guard, but that makes the code complex.
Actually, a better way to show "work being cancelled" is to have a loop or a long operation.
If I use sleep, dropping the Sleep future just stops the timer.
Let's stick to the standard implementation where the dropped future equals cancellation.
Let's make the example slightly more robust by accepting generic futures or just specific ones. A concrete example is usually better for learning.
Let's add a main to prove it works.
#[tokio::main]
async fn main() {
let winner = race_tasks().await;
println!("Winner: {}", winner);
}
One edge case: What if the user wants to handle the "cancelled" side? The select! macro doesn't have a "catch cancellation" block for the other branches easily. But the question is just "cancel the loser".
Wait, strictly speaking, select! cancels the remaining futures.
I should verify if I need to explain biased? Probably not necessary for a basic example, but good to know.
Let's double check the "cancel the loser" phrasing. Sometimes people think they need to send a signal to stop the other task. With tokio::select!, you are passing ownership of the futures to the macro. If one completes, the macro moves on and the stack frames/local variables of the other futures are dropped.
I will provide a clear, runnable code snippet.
I will define two async functions.
I will use tokio::select! in the main logic.
I will verify that the output shows the faster one winning.
Code structure:
competing_task function (simulates work).run_race function (contains select!).main function.I should mention that cancellation is done via dropping the future.
What if the tasks spawn background OS threads or tokio::spawn?
select! only cancels the future passed to it. It cannot cancel a task spawned via tokio::spawn inside that future just by dropping the future's handle (though it stops awaiting it).
I should clarify this distinction. If the "computation" is a tokio::spawn handle, dropping the handle detaches the task (it keeps running).
To cancel a JoinHandle, you usually need an AbortHandle.
However, the prompt implies simple async computations (futures), not detached tasks.
"Race two async computations" usually implies passing the futures directly.
Let's stick to passing the futures directly to select!. This is the most idiomatic use case.
Example scenario: Task A takes 1 sec. Task B takes 2 secs. A wins. B is dropped.
Let's write the code.
use tokio::time::{sleep, Duration};
// Simulate an async computation
async fn task_a() -> &'static str {
println!("Task A started");
sleep(Duration::from_millis(100)).await; // Simulate work
println!("Task A finished");
"Result A"
}
async fn task_b() -> &'static str {
println!("Task B started");
sleep(Duration::from_millis(200)).await; // Simulate work
println!("Task B finished");
"Result B"
}
// The function using select!
async fn race() -> &'static str {
tokio::select! {
res = task_a() => res,
res = task_b() => res,
}
}
Wait, tokio::select! branches must result in the same type (usually), or you handle them separately. The return type of the macro is the return type of the blocks.
If I return res in both, it works.
Is there any nuance?
"Cancel the loser".
Since tokio::select! drops the losing futures automatically, this is implicit.
I should explicitly state this in the explanation.
What if the computations are arguments? Let's make the function generic or accept arguments to make it reusable? No, simple is better.
Let's create a scenario where we can see the cancellation.
If Task B prints "Task B finished", and Task A wins, we shouldn't see "Task B finished" in the output.
Note: sleep is safe to cancel. If it were a loop, the loop would stop iterating.
Refined Plan:
race function.select!.main, call race and print the result.Code check:
tokio::select! {
res = async_function_one() => {
// Handle winner 1
res
}
res = async_function_two() => {
// Handle winner 2
res
}
}
This looks correct.
I will add a small comment about tokio::spawn. If the user wraps the computations in tokio::spawn, cancellation works differently (detaches). I will stick to direct futures to answer the prompt directly.
Final Code Structure:
use tokio::time::{sleep, Duration};
async fn computation(name: &str, delay_ms: u64) -> String {
println!("[{}] starting...", name);
sleep(Duration::from_millis(delay_ms)).await;
println!("[{}] finished!", name);
format!("{} won!", name)
}
async fn race_computations() -> String {
tokio::select! {
// Race the two computations
res = computation("Fast", 50) => {
println!("Fast branch returned.");
res
},
res = computation("Slow", 500) => {
println!("Slow branch returned.");
res
},
}
}
In the output, we will see "Fast starting", "Slow starting". Then "Fast finished", "Fast branch returned". We will not see "Slow finished" because Sleep is cancelled when select! returns.
This satisfies all constraints.
I will wrap it in a main and provide the explanation.
One detail: If using format!, I need to allocate Strings. That's fine.
I should mention biased just in case they care about the order of polling if both finish at the exact same time (e.g. 0ms), but for a general "race" example, it's not strictly required.
Wait, I should check if the user asked for a specific signature. "Construct a Rust function...". So just the function + dependencies is fine, but a full example is best.
I will formulate the response now.
tokio::select! waits for the first of several futures to complete.select! drops the remaining futures.Let's produce the output.
Dependencies needed:
tokio = { version = "1", features = ["full", "time"] } (macros, rt, time).
One tiny edge case:
If the async computation performs IO that isn't cancellable immediately, select! ensures the code after the await point doesn't run, but the underlying IO operation might complete in the background depending on the driver. But logically, the task is "cancelled" from the program's perspective. I won't overcomplicate this.
One final check on the "cancel the loser" part.
Is there any ambiguity where "cancel" implies AbortHandle?
Only if the tasks were spawned. The prompt says "async computations", which usually implies Futures/Coroutines directly. If they were threads, you'd use JoinHandle.
I will assume direct futures.
I will provide a complete, runnable example.
Steps:
tokio::time.run_race function.tokio::select!.use tokio::time::{sleep, Duration};
// A simulated async task that takes some time
async fn simulate_work(name: &'static str, duration_ms: u64) -> String {
println!("Task '{}' started (running for {}ms)", name, duration_ms);
sleep(Duration::from_millis(duration_ms)).await;
println!("Task '{}' completed", name);
format!("Result from {}", name)
}
// The function that races the tasks
pub async fn race_tasks() -> String {
// tokio::select! waits for the first branch to complete.
// The other branches (the "losers") are dropped, which cancels them.
tokio::select! {
result = simulate_work("Task A", 100) => {
println!("Task A won the race!");
result
},
result = simulate_work("Task B", 200) => {
println!("Task B won the race!");
result
},
}
}
#[tokio::main]
async fn main() {
let winner = race_tasks().await;
println!("Final Output: {}", winner);
}
This looks solid. I will format this into the final response. I will explain that dropping the future effectively cancels the computation.
Double check:
Does select! return the value from the block? Yes.
Does it automatically cancel the other? Yes.
Is biased needed? No, random (default) or implicit ordering is fine for a race.
I will write the response now. Here is a complete, runnable Rust example.
The key concept is that tokio::select! cancels the remaining branches as soon as one branch completes. In Rust, dropping a Future (the object representing an async computation) effectively cancels it.
You will need tokio in your Cargo.toml with the full features enabled for this example (specifically time and macros).
[dependencies]
tokio = { version = "1", features = ["full"] }
Here is the implementation:
use tokio::time::{sleep, Duration, Instant};
/// A simulated slow async computation.
/// It uses a loop to simulate work, checking for cancellation via `tokio::task::yield_now`.
async fn expensive_computation(id: u32, duration_ms: u64) -> String {
println!("Task {} started...", id);
let start = Instant::now();
let target = Duration::from_millis(duration_ms);
// Simulate work. In real code, this would be awaiting a network call or DB query.
// We loop in small increments to simulate a long-running task that can be interrupted.
while start.elapsed() < target {
// We use sleep here to simulate chunks of work.
// If this future is dropped (cancelled) while sleeping,
// the sleep is aborted and the function stops here.
sleep(Duration::from_millis(10)).await;
}
// If we reach here, we finished naturally
let msg = format!("Task {} finished successfully!", id);
println!("{}", msg);
msg
}
/// Races two computations using `tokio::select!`.
/// Returns the result of the winner.
async fn race_computations() -> String {
println!("--- Starting Race ---");
// `tokio::select!` waits for the first branch to complete.
// When one branch finishes, the `select!` macro returns immediately.
// Crucially, it **drops** the futures of the other branches.
// Dropping a Future cancels its execution.
tokio::select! {
res_a = expensive_computation(1, 200) => {
println!("Select: Task 1 was faster.");
res_a
},
res_b = expensive_computation(2, 50) => {
println!("Select: Task 2 was faster.");
res_b
},
}
}
#[tokio::main]
async fn main() {
let winner_result = race_computations().await;
println!("--- Race Over ---");
println!("Final result: {}", winner_result);
// Sleep briefly to ensure output prints before program exit
sleep(Duration::from_millis(100)).await;
}
select! macro. Both start executing concurrently.expensive_computation(2, ...) has a shorter duration (50ms) than Task 1 (200ms). Therefore, Task 2 finishes first. The pattern matches on the res_b branch.select! ceases to poll the future from Task 1. Since Task 1 is no longer being polled, it is dropped.
while loop inside expensive_computation for Task 1 never finishes.Drop trait would clean them up when the future was dropped.--- Starting Race ---
Task 1 started...
Task 2 started...
Task 2 finished successfully!
Select: Task 2 was faster.
--- Race Over ---
Final result: Task 2 finished successfully!
Note: Task 1 prints "started", but it never prints "finished successfully!" because it was cancelled.