首页 > 编程语言 >008 Rust 异步编程,select 宏介绍

008 Rust 异步编程,select 宏介绍

时间:2022-11-07 11:38:50浏览次数:36  
标签:function2 fn Rust tokio println async 008 select


select宏

select宏也允许并发的执行Future,但是和join、try_join不同的是,select宏只要有一个Future返回,就会返回。

示例

  • 源码
use futures::{select, future::FutureExt, pin_mut};
use tokio::runtime::Runtime;
use std::io::Result;

async fn function1() -> Result<()> {
tokio::time::delay_for(tokio::time::Duration::from_secs(10)).await;
println!("function1 ++++ ");
Ok(())
}

async fn function2() -> Result<()> {
println!("function2 ++++ ");
Ok(())
}

async fn async_main() {
let f1 = function1().fuse();
let f2 = function2().fuse();

pin_mut!(f1, f2);

select! {
_ = f1 => println!("task one completed first"),
_ = f2 => println!("task two completed first"),
}
}

fn main() {
let mut runtime = Runtime::new().unwrap();
runtime.block_on(async_main());
println!("Hello, world!");
}
  • 配置文件
[dependencies]
futures = "0.3.5"
tokio = { version = "0.2", features = ["full"] }
  • 运行结果
function2 ++++ 
task two completed first
Hello, world!


标签:function2,fn,Rust,tokio,println,async,008,select
From: https://blog.51cto.com/u_15862521/5828343

相关文章

  • 007 Rust 异步编程,通过 join 执行 Future
    前言在之前我们主要介绍了通过await和block_on执行Future,但是这两种方式实际上都是顺序执行的方式。.await是在代码块中按顺序执行,会阻塞后面的代码,但是此时会让出线程;block......
  • 006 Rust 异步编程,Stream 介绍
    Stream介绍​​Stream​​​和​​Future​​​类似,但是​​Future​​​对应的是一个​​item​​​的状态的变化,而​​Stream​​​则是类似于​​iterator​​​,在结束......
  • 005 Rust异步编程,Pin介绍
    为了对Future调用poll,需要使用到Pin的特殊类型。本节就介绍一下Pin类型。异步背后的一些原理例子1源码//文件src/main.rsusefutures::executor;asyncfnasync_function1()......
  • Rust 编程中使用 leveldb 的简单例子
    前言最近准备用Rust写一个完善的blockchain的教学demo,在持久化时考虑到使用leveldb。通过查阅文档,发现Rust中已经提供了使用leveldb的接口。将官方的例子修改了下,能够运行通......
  • 用Rust刷leetcode第八题
    ProblemImplement ​​atoi​​​ which convertsastringtoaninteger.Thefunctionfirstdiscardsasmanywhitespacecharactersasnecessaryuntilthefirst......
  • 023 通过链表学Rust之非安全方式实现链表1
    介绍视频地址:https://www.bilibili.com/video/av78062009/相关源码:https://github.com/anonymousGiga/Rust-link-list链表定义我们重新定义链表如下:pubstructList<T>{......
  • 022 通过链表学Rust之为什么要非安全的单链表
    介绍视频地址:https://www.bilibili.com/video/av78062009/相关源码:https://github.com/anonymousGiga/Rust-link-list详细内容前面我们都是使用安全的Rust编程来实现链表,但......
  • 025 通过链表学Rust之使用栈实现双端队列
    介绍视频地址:https://www.bilibili.com/video/av78062009/相关源码:https://github.com/anonymousGiga/Rust-link-list详细内容本节我们使用栈来实现双端队列。实现栈栈的实......
  • 024 通过链表学Rust之非安全方式实现链表2
    介绍视频地址:https://www.bilibili.com/video/av78062009/相关源码:https://github.com/anonymousGiga/Rust-link-list详细内容本节实现剩余的迭代器、Drop等。IntoIter实现......
  • 用Rust实现一个多线程的web server
    在本文之前,我们用Rust实现一个单线程的webserver的例子,但是单线程的webserver不够高效,所以本篇文章就来实现一个多线程的例子。单线程webserver存在的问题请求只能串行处......