如何异步读取文件?

时间:2015-12-18 17:14:58

标签: rust

我可以创建一个单独的线程来充当I / O队列,但我不确定这是否是最好的方法。它看起来是最好的。

我不知道如何使用mio加载本地文件。

2 个答案:

答案 0 :(得分:1)

我建议你自己简单地拆掉另一个帖子。 {{1}}不打算这样做,并且创建自己的异步加载器可以让您完全控制读/写的发生方式和时间,这一点非常重要,如果性能是您的目标(正如我想象的那样,如果你需要异步磁盘I / O)。您可以选择是写入/读取单个字节,单行还是累加块并写入它们。如果您的应用程序在其他时间等待其他时间,例如网络,则可以选择写入磁盘,例如。

答案 1 :(得分:0)

使用tokio :: fs :: read:

use tokio::prelude::Future;

fn main() {
    let task = tokio::fs::read("/proc/cpuinfo").map(|data| {
        // do something with the contents of the file ...
        println!("contains {} bytes", data.len());
        println!("{:?}", String::from_utf8(data));
    }).map_err(|e| {
        // handle errors
        eprintln!("IO error: {:?}", e);
    });
    tokio::run(task);
}