rust 同时处理多个异步任务

rust 复制代码
use tokio::{sync::oneshot, time::{sleep, Duration}};

async fn check_for_one() {
    // This loop will continuously print "write" every second until interrupted
    loop {
        println!("write");
        sleep(Duration::from_secs(1)).await; // Non-blocking sleep in async context
    }
}

#[tokio::main]
async fn main() {
    // Create a oneshot channel
    let (tx1, rx1) = oneshot::channel::<&str>();

    // Spawn a task that sends a message after 2 seconds
    tokio::spawn(async move {
        sleep(Duration::from_secs(2)).await;    
        let _ = tx1.send("one");
    });

    // Use tokio::select! to wait for either the print task or the message on rx1
    tokio::select! {
        _ = check_for_one() => {
            // This branch will continuously print "write" every second
            println!("check_for_one completed");
        }
        val = rx1 => {
            // This branch will be executed once the message is received from rx1
            match val {
                Ok(val) => println!("rx1 completed first with {:?}", val),
                Err(e) => println!("Failed to receive from rx1: {:?}", e),
            }
        }
    }

    println!("main thread exiting"); 
}

只要有一个异步任务完成,就会退出select! 。

相关推荐
LHICOD几秒前
Linux-2
java·linux·后端·jar·vmware·svm·vm
香蕉大香蕉(06敬畏市场)1 分钟前
MySQL 单点详解(03)
java·数据库·mysql·面试·八股·大厂实习
赤生云电竞3 分钟前
云游戏边缘节点部署:机房选址与网络拓扑优化实践——接入延迟、VXLAN与GPU虚拟化选型
数据库·游戏
呆呆敲代码的小Y21 分钟前
【实战精选面试题】C# 面试题详细解答,按难易程度排序
android·java·游戏·c#·游戏开发·unity面试题·c#面试题
geovindu23 分钟前
rust: Semaphore Pattern
开发语言·后端·设计模式·rust·代理模式·企业级信号量模式·同步型模式
水无痕simon37 分钟前
3、工程重构
java·spring cloud·重构
阿里云基础软件1 小时前
Agent 任务提速 10.71%,内存占用降低 21.60%|Alibaba Cloud Linux 4 重大发布
java·linux·人工智能·操作系统·agent
Y001 小时前
PostgreSQL 权限管理踩坑记:从 42501 到默认权限和 RLS
数据库·postgresql
呆萌很1 小时前
达梦(DM8)数据库常用SQL
数据库·sql
跟太阳说早安1 小时前
极简数据库SQL
数据库·sql