RUST Ex00 Async-std

Posted wr786

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了RUST Ex00 Async-std相关的知识,希望对你有一定的参考价值。

RUST Ex00 Async-std

1 使用Async-std

首先来看一个普通的函数:

use std::fs::File;
use std::io::{self, Read};

fn read_file(path: &str) -> io::Result<String> {
    let mut file = File::open(path)?;
    let mut buffer = String::new();
    file.read_to_string(&mut buffer)?;
    Ok(buffer)
}

将这个函数用Async-std改成异步函数只需要改成这样:

use async_std::fs::File;
use async_std::prelude::*;
use async_std::io;

async fn read_file(path: &str) -> io::Result<String> {
    let mut file = File::open(path).await?;
    let mut buffer = String::new();
    file.read_to_string(&mut buffer).await?;
    Ok(buffer)
}

嗯,没错,只要将std替换成async-std,并且在适当的位置加上async或者await即可。

We used async-std internally. We just replaced "std" by "async-std" and added "async" / "await" at the right places. ——Pascal Hertleif

2 浅析Async-std

async

简单来说,在函数前使用async关键词等价于:

use async_std::fs::File;
use async_std::prelude::*;
use async_std::io;

fn read_file(path: &str) -> impl Future<Item=io::Result<String>> {
    let mut file = File::open(path).await?;
    let mut buffer = String::new();
    file.read_to_string(&mut buffer).await?;
    Ok(buffer)
}

.await

如同字面意思,.await标注了需要等待运行完成的地方。

fn main() {
    let data = read_file("./Cargo.toml");
    // futures do nothing unless you '.await' or poll them
}
  • Async函数在被调用时生成futures

3 部分要素

  • async_std::task
    • task::block_on This blocks the main thread, executes the future and wait for it to come back.
    • task::spawn This runs a background task and then waits for its completion, blocking the main thread.
    • task::spawn_blocking The returned JoinHandle is exactly the same as for a blocking task.
  • .race
  • .join futures-rs also provides join_all, joining multiple futures
  • async_std::sync::channel

4 AsyncRead/Write/Seek

  • AsyncRead: Read from a socket, asynchronously
  • AsyncWrite: Write to a socket, asynchronously
  • AsyncSeek: Write to a socket, asynchronously

例如:

fn read_from_tcp(socket: async_std::net::TcpSocket) {
    // for applications
}

参考

async/.await with async-std by Florian Gilcher

以上是关于RUST Ex00 Async-std的主要内容,如果未能解决你的问题,请参考以下文章

00_Rust安装及Hello World

这些代码使用 Rust Dashmap 会产生死锁吗?

RUST 0x00 START::DASH

Rust chrono 给出 ParseError(NotEnough) [重复]

学习笔记:python3,代码片段(2017)

无法找到指定dll库文件skinH_EL.dll中的输出命令skinH_Attach_EX_