• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

rust学习-同时执行多Future

武飞扬头像
~kiss~
帮助1

只用 .await 来执行future,会阻塞并发任务,直到特定的 Future 完成

join!:等待所有future完成

可事实上为什么都是res1完成后再执行res2?
join! 不保证并发执行,难道只负责同步等待?

示例

[package]
name = "rust_demo5"
version = "0.1.0"
edition = "2021"

[dependencies]
futures = "0.3"
tokio = {
    version = "1.16.0", features = ["full"] }
tokio-stream = "0.1.14"
use futures::executor::block_on;
use std::thread::sleep;
use std::thread;
use std::time::Duration;
use futures::{
   future, join};

async fn task_one() {
   
	println!("task_one: begin");
    thread::sleep(Duration::from_secs(4));
	println!("task_one: finish");
}

async fn task_two() {
   
	println!("task_two: begin");
    thread::sleep(Duration::from_secs(2));
	println!("task_two: finish");
}

#[tokio::main]
async fn main() {
   
    let (res1, res2) = join!(task_one(), task_two());
    // 在这里调用 res1 和 res2,它们分别对应异步任务1和异步任务2的输出结果
    // 先执行完task_one,再执行完task_two,然后再返回
}
学新通
use futures::executor::block_on;
use std::thread;
use futures::{
   future, join};

async fn task_one() {
   
	println!("task_one: begin");
    for i in 1..=10_000_000 {
   
        if i % 100_000 == 0 {
   
            println!("task_one,  found a number: {}", i);
        }
    }
	println!("task_one: finish");
}

async fn task_two() {
   
	println!("task_two: begin");
    for i in 1..=10_000_000 {
   
        if i % 100_000 == 0 {
   
            println!("task_two,  found a number: {}", i);
        }
    }
	println!("task_two: finish");
}

#[tokio::main]
async fn main() {
   
    let (res1, res2) = join!(task_one(), task_two());
    // 在这里调用 res1 和 res2,它们分别对应异步任务1和异步任务2的输出结果
}
学新通

反例

不必在 get_book 完成后再 get_music

async fn get_book_and_music() -> (Book, Music) {
   
    let book = get_book().await;
    let music = get_music().await;
    (book, music)
}

try_join

返回 Result 的 future,考虑使用 try_join! 而非 join
join 只会在所有子 future 都完成后才会完成,它甚至会在子 future 返回 Err 之后继续处理
try_join! 会在其中的子future返回错误后立即完成

use futures::try_join;

async fn get_book() -> Result<Book, String> {
    /* ... */ Ok(Book) }
async fn get_music() -> Result<Music, String> {
    /* ... */ Ok(Music) }

async fn get_book_and_music() -> Result<(Book, Music), String> {
   
    let book_fut = get_book();
    let music_fut = get_music();
    try_join!(book_fut, music_fut)
}

传进 try_join! 的 future 必须要用相同的错误类型。
考虑使用 futures::future::TryFutureExt 库的 .map_err(|e| …) 或 err_into() 函数来统一错误类型:

use futures::{
   
    future::TryFutureExt,
    try_join,
};

// Result 类型用于更好地处理和组织错误情况,并在避免出现非预期错误时提供便捷

// 一种是一个内部类型为 Book 的成功结果,另一个是一个无内部类型 () 的错误结果
async fn 

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgekkkf
系列文章
更多 icon
同类精品
更多 icon
继续加载