gpt4 book ai didi

rust - 如何删除传递给 futures-cpupool 的闭包环境?

转载 作者:行者123 更新时间:2023-11-29 08:06:16 24 4
gpt4 key购买 nike

我有以下代码:

extern crate futures;
extern crate futures_cpupool;
extern crate tokio_timer;

use std::time::Duration;

use futures::Future;
use futures_cpupool::CpuPool;
use tokio_timer::Timer;

fn work(foo: Foo) {
std::thread::sleep(std::time::Duration::from_secs(10));
}

#[derive(Debug)]
struct Foo { }

impl Drop for Foo {
fn drop(&mut self) {
println!("Dropping Foo");
}
}

fn main() {
let pool = CpuPool::new_num_cpus();

let foo = Foo { };

let work_future = pool.spawn_fn(|| {
let work = work(foo);

let res: Result<(), ()> = Ok(work);
res
});

println!("Created the future");

let timer = Timer::default();
let timeout = timer.sleep(Duration::from_millis(750))
.then(|_| Err(()));

let select = timeout.select(work_future).map(|(win, _)| win);

match select.wait() {
Ok(()) => { },
Err(_) => { },
}
}

这段代码似乎没有执行 Foo::drop - 没有打印任何消息。

我预计 foo 将在 select 中的 timeout future 解决后立即被删除,因为它是闭包环境的一部分,通过到下降的 future 。

如何让它执行Foo::drop

最佳答案

documentation for CpuPool states :

The worker threads associated with a thread pool are kept alive so long as there is an open handle to the CpuPool or there is work running on them. Once all work has been drained and all references have gone away the worker threads will be shut down.

此外,您转让了 foo 的所有权来自 main到闭包,然后将其转移到 work . work会掉落 foo在 block 的末尾。然而,work也在执行阻塞 sleep 操作。此 sleep 计为线程上运行的工作。

当主线程退出时 sleep 还在继续,这会立即破坏程序和所有线程,没有任何时间清理。

正如 How to terminate or suspend a Rust thread from another thread? 中指出的那样(以及其他语言的其他问题),没有安全的方法来终止线程。

I expected foo to be dropped as soon as timeout future resolves in select, as it's a part of environment of a closure, passed to dropped future.

future 实际上并没有“拥有”闭包或 foo .它只有一个线程句柄:

pub struct CpuFuture<T, E> {
inner: Receiver<thread::Result<Result<T, E>>>,
keep_running_flag: Arc<AtomicBool>,
}

奇怪的是,the docs say :

If the returned future is dropped then this CpuPool will attempt to cancel the computation, if possible. That is, if the computation is in the middle of working, it will be interrupted when possible.

但是,我没有看到 Drop 的任何实现对于 CpuFuture , 所以我不明白它怎么可能(或安全)。而不是 Drop ,线程池本身运行一个 Future .当轮询该 future 时,它会检查接收器是否已被丢弃。此行为由 oneshot::Receiver 提供.但是,这与线程无关,线程在未来的视野之外。

关于rust - 如何删除传递给 futures-cpupool 的闭包环境?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43482581/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com