use std::thread;
use tokio::{sync::mpsc,time::{sleep, Duration},
};async fn check_for_one() {// 該函數會每秒打印一次 "write"loop {println!("write");sleep(Duration::from_secs(1)).await;}
}async fn start_print_task() -> Result<(), ()> {// 在新線程中運行 Tokio 運行時thread::spawn(move || {// 創建一個新的 Tokio 運行時let rt = tokio::runtime::Runtime::new().unwrap_or_else(|e| panic!("Failed to create Tokio runtime: {}", e));// 使用 Tokio 運行時執行異步任務rt.block_on(async move {check_for_one().await;});});// 返回一個已完成的 Future,方便配合 select! 使用sleep(Duration::from_secs(1)).await;Ok::<(), ()>(())
}#[tokio::main]
async fn main() {// 創建一個只發送“信號”的通道,類型為 ()let (tx, mut rx) = mpsc::channel::<()>(1);// 啟動打印任務,返回一個 Futurelet print_task = start_print_task();// 啟動另一個異步任務,2 秒后向通道發送“信號”tokio::spawn(async move {sleep(Duration::from_secs(2)).await;let _ = tx.send(()).await;});// 使用 tokio::select! 監聽tokio::select! {val = rx.recv() => {match val {Some(_) => println!("rx1 completed first with signal"),None => println!("rx1 channel closed"),}}_ = print_task => {println!("start_print_task completed");}}println!("main thread exiting");
}
使用select!宏 ,來完成 只要有一個異步任務完成,就會退出異步監聽。