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

相关推荐
qq_203769497 分钟前
debian13安装PostgreSQL并远程连接
数据库·postgresql
苏小瀚12 分钟前
[MySQL] 联合查询
数据库·mysql
雪碧聊技术14 分钟前
Linux命令过关挑战
linux·运维·数据库
青鱼入云15 分钟前
Java 11对集合类做了哪些增强?
java
qq_124987075323 分钟前
基于Spring Boot的高校实习实践管理系统(源码+论文+部署+安装)
java·spring boot·后端·毕业设计
oak隔壁找我28 分钟前
SpringBoot + MyBatis 配置详解
java·数据库·后端
oak隔壁找我28 分钟前
SpringBoot + Redis 配置详解
java·数据库·后端
躺平的赶海人32 分钟前
C# Dictionary 线程安全指南:多线程下操作 Dictionary<string, DateTime> 的加锁策略
java·安全·c#
帧栈41 分钟前
开发避坑指南(64):修复IllegalArgumentException:参数值类型与期望类型不匹配
java·数据库
坐不住的爱码42 分钟前
ArrayList和LinkedList的区别
java