Rust:连接线程失败,并显示:无法移出取消引用"std::sync::muttexGuard<"_,模型::worker::worker>



我很难弄清楚如何解决这个问题。

因此,我有一个类ArcWorker,其中包含对Worker的共享引用(正如您可以在下面备注的那样(。

我在ArcWorker中编写了一个名为join()的函数,其中self.internal.lock().unwrap().join();行失败,并出现以下错误:

无法移出std::sync::MutexGuard<'_, models::worker::Worker>的取消引用

通过这一行,我试图锁定互斥对象,打开包装并从Worker类调用join()函数。

据我所知,一旦锁函数被调用,并且它借用了对self(&self(的引用,那么我需要一些方法来按值传递self以进行联接(std::thread的联接函数需要按值传递self(。

我该怎么做才能让它发挥作用?我试了好几个小时才找到问题的答案,但没有成功。

pub struct Worker {
accounts: Vec<Arc<Mutex<Account>>>,
thread_join_handle: Option<thread::JoinHandle<()>>
}
pub struct ArcWorker {
internal: Arc<Mutex<Worker>>
}
impl ArcWorker {
pub fn new(accounts: Vec<Arc<Mutex<Account>>>) -> ArcWorker {
return ArcWorker {
internal: Arc::new(Mutex::new(Worker {
accounts: accounts,
thread_join_handle: None
}))
}
}
pub fn spawn(&self) {
let local_self_1 = self.internal.clone();

self.internal.lock().unwrap().thread_join_handle = Some(thread::spawn(move || {
println!("Spawn worker");
local_self_1.lock().unwrap().perform_random_transactions();
}));
}
pub fn join(&self) {
self.internal.lock().unwrap().join();
}
}
impl Worker {
fn join(self) {
if let Some(thread_join_handle) = self.thread_join_handle {
thread_join_handle.join().expect("Couldn't join the associated threads.")
}
}
fn perform_random_transactions(&self) {

}
}

由于您已经在选项中持有JoinHandle,因此可以使Worker::join()&mut self而不是self,并将if let条件更改为:

// note added `.take()`
if let Some(thread_join_handle) = self.thread_join_handle.take() {

Option::take()将把句柄从选项中移出并赋予您对它的所有权,同时把None留在self.thread_join_handle中。通过此更改,ArcWorker::join()应按原样编译。

最新更新