gpt4 book ai didi

multithreading - “closure may outlive the current function”用作参数

转载 作者:行者123 更新时间:2023-12-03 11:49:02 25 4
gpt4 key购买 nike

我试图将函数作为参数传递并在线程内调用它。这是我要运行的代码:

use std::thread;

pub struct Image {
pub data: Vec<u8>,
}

pub trait ImageHandler {
fn get_image(&self) -> Option<Image>;
}

pub struct Window {
pub id: usize,
}

impl ImageHandler for Window {
fn get_image(&self) -> Option<Image> {
None
}
}

fn test(func: impl Fn() -> Option<Image> + Sync + Send + 'static) -> thread::JoinHandle<()> {
thread::spawn(move || {
let _image = func().unwrap();
})
}

fn main() {
let window = Window { id: 0 };
test(&|| window.get_image());
}

我收到以下错误:
error[E0373]: closure may outlive the current function, but it borrows `window`, which is owned by the current function
--> src/main.rs:30:11
|
30 | test(&|| window.get_image());
| ^^ ------ `window` is borrowed here
| |
| may outlive borrowed value `window`
|
note: function requires argument type to outlive `'static`
--> src/main.rs:30:5
|
30 | test(&|| window.get_image());
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: to force the closure to take ownership of `window` (and any other referenced variables), use the `move` keyword
|
30 | test(&move || window.get_image());
| ^^^^^^^

error[E0716]: temporary value dropped while borrowed
--> src/main.rs:30:11
|
30 | test(&|| window.get_image());
| ------^^^^^^^^^^^^^^^^^^^^^-- temporary value is freed at the end of this statement
| | |
| | creates a temporary which is freed while still in use
| argument requires that borrow lasts for `'static`

我认为 Fn对于将其发送到线程应该是静态的,但是当我将其生存期更改为 'static时,它会提示。
我也不知道是否可以使用 ImageHandler作为参数。我不知道这一点。

最佳答案

如果闭包可以超过当前线程的生命周期,那么它应该拥有所需变量的所有权:

fn main() {
let window = Window { id: 0 };
test(move || window.get_image());
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=9cbf953b79e80e280156688d083f94fb有游乐场。

但是,由于(我想)这只是一个玩具示例,因此此修复程序可能适用于或可能不适用于您的实际用例。如果变得更加复杂,则可以尝试说服编译器,使您知道闭包不会超过当前线程的生命周期(可能使用辅助包装箱),或者诉诸其他技术。

关于multithreading - “closure may outlive the current function”用作参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61331026/

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