[英]The current SynchronizationContext may not be used as a TaskScheduler
[英]“closure may outlive the current function” while used as a parameter
我正在嘗試將 function 作為參數傳遞並在線程內調用它。 這是我要運行的代碼:
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 用於將其發送到線程但是當我將其生命周期更改為'static
時,它會抱怨。 另外我不知道是否可以使用ImageHandler
作為參數。 我想不通。
如果閉包可以比當前線程壽命更長,它應該擁有它需要的變量的所有權:
fn main() {
let window = Window { id: 0 };
test(move || window.get_image());
}
但是,(我猜)這只是一個玩具示例,此修復可能適用於您的實際用例,也可能不適用於您的實際用例。 如果它變得更復雜,您可以嘗試讓編譯器相信您知道閉包不會超過當前線程(可能使用輔助板條箱)或訴諸其他技術。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.