Kah*_*ler 5 asynchronous future rust
Rust 有async
可以与Abortable
期货相关联的方法。文档说,中止时:
未来将立即完成,没有任何进一步的进展。
绑定到未来的任务所拥有的变量会被删除吗?如果这些变量实现了drop
,会drop
被调用吗?如果未来产生了其他未来,它们是否会在一个链中流产?
例如:在下面的代码片段中,我没有看到为中止的任务发生析构函数,但我不知道它是否未被调用或发生在未显示打印的单独线程中。
use futures::executor::block_on;
use futures::future::{AbortHandle, Abortable};
struct S {
i: i32,
}
impl Drop for S {
fn drop(&mut self) {
println!("dropping S");
}
}
async fn f() -> i32 {
let s = S { i: 42 };
std::thread::sleep(std::time::Duration::from_secs(2));
s.i
}
fn main() {
println!("first test...");
let (abort_handle, abort_registration) = AbortHandle::new_pair();
let _ = Abortable::new(f(), abort_registration);
abort_handle.abort();
std::thread::sleep(std::time::Duration::from_secs(1));
println!("second test...");
let (_, abort_registration) = AbortHandle::new_pair();
let task = Abortable::new(f(), abort_registration);
block_on(task).unwrap();
std::thread::sleep(std::time::Duration::from_secs(1));
}
Run Code Online (Sandbox Code Playgroud)
是的,已经创建的值将被删除。
在您的第一个示例中,f
永远不会开始返回的未来,因此S
永远不会创建 。这意味着它不能被丢弃。
在第二个示例中,该值被删除。
如果您同时运行未来并中止它,这将更加明显。在这里,我产生了两个并发的期货:
S
并等待 200 毫秒use futures::future::{self, AbortHandle, Abortable};
use std::time::Duration;
use tokio::time;
struct S {
i: i32,
}
impl S {
fn new(i: i32) -> Self {
println!("Creating S {}", i);
S { i }
}
}
impl Drop for S {
fn drop(&mut self) {
println!("Dropping S {}", self.i);
}
}
#[tokio::main]
async fn main() {
let create_s = async {
let s = S::new(42);
time::delay_for(Duration::from_millis(200)).await;
println!("Creating {} done", s.i);
};
let (abort_handle, abort_registration) = AbortHandle::new_pair();
let create_s = Abortable::new(create_s, abort_registration);
let abort_s = async move {
time::delay_for(Duration::from_millis(100)).await;
abort_handle.abort();
};
let c = tokio::spawn(create_s);
let a = tokio::spawn(abort_s);
let (c, a) = future::join(c, a).await;
println!("{:?}, {:?}", c, a);
}
Run Code Online (Sandbox Code Playgroud)
use futures::future::{self, AbortHandle, Abortable};
use std::time::Duration;
use tokio::time;
struct S {
i: i32,
}
impl S {
fn new(i: i32) -> Self {
println!("Creating S {}", i);
S { i }
}
}
impl Drop for S {
fn drop(&mut self) {
println!("Dropping S {}", self.i);
}
}
#[tokio::main]
async fn main() {
let create_s = async {
let s = S::new(42);
time::delay_for(Duration::from_millis(200)).await;
println!("Creating {} done", s.i);
};
let (abort_handle, abort_registration) = AbortHandle::new_pair();
let create_s = Abortable::new(create_s, abort_registration);
let abort_s = async move {
time::delay_for(Duration::from_millis(100)).await;
abort_handle.abort();
};
let c = tokio::spawn(create_s);
let a = tokio::spawn(abort_s);
let (c, a) = future::join(c, a).await;
println!("{:?}, {:?}", c, a);
}
Run Code Online (Sandbox Code Playgroud)
请注意,我已切换到 Tokio 以便能够使用time::delay_for
,因为您永远不应在异步函数中使用阻塞操作。
也可以看看:
如果未来产生了其他期货,它们是否会在一个链中流产?
不,当你spawn
成为未来时,它与它产生的地方断开连接。
也可以看看:
归档时间: |
|
查看次数: |
1147 次 |
最近记录: |