我阅读了tokio文档,我想知道将来封装昂贵的同步I/O的最佳方法是什么.
使用reactor框架,我们可以获得绿色线程模型的优势:一些OS线程通过执行程序处理大量并发任务.
未来的tokio模型是需求驱动的,这意味着未来本身将轮询其内部状态以提供有关其完成的信息; 允许背压和取消功能.据我了解,未来的投票阶段必须是非阻塞才能运作良好.
I/OI想要封装可以看作是一个长期的原子和昂贵的操作.理想情况下,独立任务将执行I/O,并且相关联的未来将轮询I/O线程以获得完成状态.
我看到的两个唯一选择是:
poll在将来的功能中.据我所知,这两种解决方案都不是最优的,并且没有充分利用绿色线程模型(首先不在文档中建议,其次不通过reactor框架提供的执行程序).还有其他解决方案吗?
我试图理解Future::select:在这个例子中,首先返回具有较长时间延迟的未来.
当我通过它的例子阅读这篇文章时,我得到了认知失调.作者写道:
该
select函数运行两个(或者更多select_all)期货,并返回第一个完成.这对于实现超时很有用.
看来我不明白这种感觉select.
extern crate futures;
extern crate tokio_core;
use std::thread;
use std::time::Duration;
use futures::{Async, Future};
use tokio_core::reactor::Core;
struct Timeout {
time: u32,
}
impl Timeout {
fn new(period: u32) -> Timeout {
Timeout { time: period }
}
}
impl Future for Timeout {
type Item = u32;
type Error = String;
fn poll(&mut self) -> Result<Async<u32>, Self::Error> {
thread::sleep(Duration::from_secs(self.time as u64));
println!("Timeout is done with time {}.", …Run Code Online (Sandbox Code Playgroud) 我想知道这个关于期货的老问题的答案是否仍然适用于更新的语言结构async/await。似乎是这样,因为下面的代码打印:
hello
good bye
hello
Run Code Online (Sandbox Code Playgroud)
虽然指南说
futures::join 宏可以等待多个不同的 future 完成,同时执行它们。
显然,对于许多其他异步系统(例如, node.js)而言,这是对预期行为的转移sleep。
有什么根本原因吗?
hello
good bye
hello
Run Code Online (Sandbox Code Playgroud)
添加:实际线程预期的行为 (I)
fn main() {
let fut1 = do_async( move || {
println!( "hello" );
thread::sleep( Duration::from_millis( 3000 ) );
println!( "good bye" );
});
let fut2 = do_async( move || {
println!( "hello" );
});
fut1();
fut2();
}
Run Code Online (Sandbox Code Playgroud)
use std::time::Duration;
use std::thread;
async fn sayHiOne() {
println!( " hello " );
thread::sleep( Duration::from_millis( …Run Code Online (Sandbox Code Playgroud)