在像C#这样的语言中,给出这个代码(我没有await故意使用关键字):
async Task Foo()
{
var task = LongRunningOperationAsync();
// Some other non-related operation
AnotherOperation();
result = task.Result;
}
Run Code Online (Sandbox Code Playgroud)
在第一行中,long操作在另一个线程中运行,并Task返回a(即未来).然后,您可以执行另一个与第一个并行运行的操作,最后,您可以等待操作完成.我认为,这也是行为async/ await在Python,JavaScript等
另一方面,在Rust中,我在RFC中读到:
Rust的期货与其他语言的期货之间的根本区别在于,除非进行调查,否则Rust的期货不会做任何事情.整个系统是围绕这个建立的:例如,取消正在降低未来正是出于这个原因.相比之下,在其他语言中,调用异步fn会旋转一个立即开始执行的未来.
在这种情况下,是什么目的async/ await鲁斯特?看到其他语言,这种表示法是一种运行并行操作的便捷方式,但是如果调用async函数没有运行任何东西,我无法看到它在Rust中是如何工作的.
我阅读了tokio文档,我想知道将来封装昂贵的同步I/O的最佳方法是什么.
使用reactor框架,我们可以获得绿色线程模型的优势:一些OS线程通过执行程序处理大量并发任务.
未来的tokio模型是需求驱动的,这意味着未来本身将轮询其内部状态以提供有关其完成的信息; 允许背压和取消功能.据我了解,未来的投票阶段必须是非阻塞才能运作良好.
I/OI想要封装可以看作是一个长期的原子和昂贵的操作.理想情况下,独立任务将执行I/O,并且相关联的未来将轮询I/O线程以获得完成状态.
我看到的两个唯一选择是:
poll在将来的功能中.据我所知,这两种解决方案都不是最优的,并且没有充分利用绿色线程模型(首先不在文档中建议,其次不通过reactor框架提供的执行程序).还有其他解决方案吗?
我正在尝试构建一个对象,该对象可以管理来自 websocket 的提要,但能够在多个提要之间切换。
有一个Feed特点:
trait Feed {
async fn start(&mut self);
async fn stop(&mut self);
}
Run Code Online (Sandbox Code Playgroud)
共有三个结构体实现Feed:A、B和C。
当start被调用时,它会启动一个无限循环,监听来自 websocket 的消息并处理每条传入的消息。
我想实现一个FeedManager维护单个活动源但可以接收命令来切换它正在使用的源的命令。
enum FeedCommand {
Start(String),
Stop,
}
struct FeedManager {
active_feed_handle: tokio::task::JoinHandle,
controller: mpsc::Receiver<FeedCommand>,
}
impl FeedManager {
async fn start(&self) {
while let Some(command) = self.controller.recv().await {
match command {
FeedCommand::Start(feed_type) => {
// somehow tell the active feed to stop (need channel probably) or …Run Code Online (Sandbox Code Playgroud) 我试图理解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) rust ×4
future ×3
async-await ×1
asynchronous ×1
performance ×1
rust-tokio ×1
select ×1
syntax ×1