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

相关推荐
庞轩px4 分钟前
MinorGC的完整流程与复制算法深度解析
java·jvm·算法·性能优化
zhouping@6 分钟前
JAVA学习笔记day06
java·笔记·学习
haixingtianxinghai19 分钟前
Redis真的是单线程吗?
数据库·redis·缓存
毕设源码-郭学长24 分钟前
【开题答辩全过程】以 某某协会管理与展示平台为例,包含答辩的问题和答案
java
多云的夏天30 分钟前
docker容器部署-windows-ubuntu
java·docker·容器
庞轩px38 分钟前
内存区域的演进与直接内存——JVM性能优化的权衡艺术
java·jvm·笔记·性能优化
FirstFrost --sy40 分钟前
MySQL复合查询
数据库·mysql
编码忘我1 小时前
java多线程安全集合
java
imuliuliang1 小时前
MySQL的底层原理与架构
数据库·mysql·架构
悟空码字1 小时前
滑块拼图验证:SpringBoot完整实现+轨迹验证+Redis分布式方案
java·spring boot·后端