我需要创建一个线程并将线程连接句柄存储在结构体中,但是我得到了错误:
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
pub struct NetworkReceiver {
terminate_flag: AtomicBool,
join_handle: Option<thread::JoinHandle<()>>,
}
impl NetworkReceiver {
pub fn new() -> NetworkReceiver {
NetworkReceiver {
terminate_flag: AtomicBool::new(false),
join_handle: None,
}
}
pub fn start(&mut self) {
self.join_handle = Some(thread::spawn(|| self.run()));
}
pub fn run(&mut self) {
while !self.terminate_flag.load(Ordering::Relaxed) {
// ...
}
}
pub fn terminate(&mut self) {
self.terminate_flag.store(true, Ordering::Relaxed);
}
}
error[E0506]: cannot assign to `self.join_handle` because it is borrowed
--> src/main.rs:18:9
|
18 | self.join_handle = Some(thread::spawn(|| self.run()));
| ^^^^^^^^^^^^^^^^ ----------------------------
| | | | |
| | | | borrow occurs due to use in closure
| | | borrow of `self.join_handle` occurs here
| | argument requires that `*self` is borrowed for `'static`
| assignment to borrowed `self.join_handle` occurs here
error[E0521]: borrowed data escapes outside of associated function
--> src/main.rs:18:33
|
17 | pub fn start(&mut self) {
| ---------
| |
| `self` is a reference that is only valid in the associated function body
| let's call the lifetime of this reference `'1`
18 | self.join_handle = Some(thread::spawn(|| self.run()));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| |
| `self` escapes the associated function body here
| argument requires that `'1` must outlive `'static`
2条答案
按热度按时间htrmnn0y1#
您可以将
join_handle
与NetworkReceiver
中的其他内容分开,如下所示:如果你需要对
NetworkReceiver
内部的任何东西进行独占访问,那么你必须把它(或者需要它的部分) Package 在RwLock
或Mutex
或类似的东西中。8ulbf1ek2#
当在线程中使用变量时,该线程必须拥有所有权。
(thread::spawn(|| self.run());
这一行试图将self
移入线程,但由于self
需要比函数更长的寿命,因此无法移入。我相信你必须将你的NetworkReceiver封装在一个Arc互斥体中。你可以改变你的
NetworkReceiver::new()
来返回一个Arc,并且所有相关的函数将从fn foo(&mut self)
改变为fn foo(self: Arc<Self>)