How to Implement Cooperative Cancellation in Async Rust

Implement cooperative cancellation in async Rust using tokio::select! to run concurrent tasks and stop them immediately upon completion or timeout.

Use tokio::select! to run multiple async tasks concurrently and cancel the remaining ones when any task completes or a timeout occurs.

use tokio::time::{timeout, Duration};

async fn cooperative_cancel() {
    let task1 = async { /* long running work */ };
    let task2 = async { /* another task */ };

    tokio::select! {
        _ = task1 => println!("Task 1 finished"),
        _ = task2 => println!("Task 2 finished"),
        _ = tokio::time::sleep(Duration::from_secs(5)) => println!("Timeout"),
    }
}