- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下代码:
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 inselect
, 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/
我正在使用 tokio 和 futures-cpupool 编写一个简单的 RPC 服务器。服务器持有一个 BTreeMap 盒装闭包,函数名称作为键。当前的实现非常简单: pub struct Sl
我正在创建一个 futures_cpupool::CpuPool,其中每个线程都需要打开数据库连接,这是一个代价高昂的初始化。这些初始化的状态需要在作业之间保持不变,因为它们需要很长时间才能设置。数据
我有以下代码: extern crate futures; extern crate futures_cpupool; extern crate tokio_timer; use std::time:
我在使用 cpu pools 时遇到了奇怪的行为: #[macro_use] extern crate lazy_static; extern crate tokio_core; extern cra
背景 我正在开发一个通过 r2d2 使用 diesel 的 actix-web 应用程序,我不确定如何最好地进行异步查询。我找到了三个看似合理的选项,但不确定哪一个是最好的。 可能的解决方案 同步 A
我是一名优秀的程序员,十分优秀!