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

相关推荐
花褪残红青杏小5 小时前
Rust图像处理第8节-暗角 & 复古胶片特效:四周衰减中心高亮
rust·webassembly·图形学
倔强的石头_10 小时前
《Kingbase护城河》——猎捕慢查询:执行计划的微观解析与索引调优实战
数据库
SelectDB12 小时前
Apache Doris Python UDF:让 SQL 直接调用 Python 生态,支撑 Agent 时代复杂业务逻辑
大数据·数据库·python
Flittly13 小时前
【AgentScope Java新手村系列】(16)从RAG到多路检索
java·spring boot·spring
小兔崽子去哪了13 小时前
Java 生成二维码解决方案
java·后端
人活一口气18 小时前
从JVM调优到MCP协议:Java全栈技术体系深度总结与企业级架构实践
java·spring boot
NE_STOP20 小时前
Vibe Coding -- 完整项目案例实操
java
荣码20 小时前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python
SimonKing20 小时前
Google第三方授权登录
java·后端·程序员
独孤留白20 小时前
从C到Rust:Rust 的 Trait 不是Interface,那是什么?
rust