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! 。

相关推荐
海边的Kurisu1 小时前
苍穹外卖日记 | Day1 苍穹外卖概述、开发环境搭建、接口文档
java
C雨后彩虹4 小时前
任务最优调度
java·数据结构·算法·华为·面试
heartbeat..4 小时前
Spring AOP 全面详解(通俗易懂 + 核心知识点 + 完整案例)
java·数据库·spring·aop
Jing_jing_X4 小时前
AI分析不同阶层思维 二:Spring 的事务在什么情况下会失效?
java·spring·架构·提升·薪资
元Y亨H6 小时前
Nacos - 服务发现
java·微服务
麦聪聊数据6 小时前
MySQL并发与锁:从“防止超卖”到排查“死锁”
数据库·sql·mysql
微露清风6 小时前
系统性学习C++-第十八讲-封装红黑树实现myset与mymap
java·c++·学习
dasi02276 小时前
Java趣闻
java
AC赳赳老秦7 小时前
DeepSeek 私有化部署避坑指南:敏感数据本地化处理与合规性检测详解
大数据·开发语言·数据库·人工智能·自动化·php·deepseek
阿波罗尼亚7 小时前
Tcp SSE Utils
android·java·tcp/ip