Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Multithreading 为什么等待线程完成的锈代码不起作用?_Multithreading_Rust - Fatal编程技术网

Multithreading 为什么等待线程完成的锈代码不起作用?

Multithreading 为什么等待线程完成的锈代码不起作用?,multithreading,rust,Multithreading,Rust,我有一些多线程代码给我带来了麻烦。这很简单,我可以复制它: 使用std::thread; 使用std::时间; 使用std::sync:{Arc,AtomicBool}}; 使用std::ops::Drop; 结构容器{ //线程的连接句柄 th:选项, //当我们希望线程退出时,设置为true 停止线程:圆弧, } impl容器{ fn new()->Self{ //创建新实例 让mut inst=Self{ th:没有, 停止线程:Arc::new(AtomicBool::new(false

我有一些多线程代码给我带来了麻烦。这很简单,我可以复制它:

使用std::thread;
使用std::时间;
使用std::sync:{Arc,AtomicBool}};
使用std::ops::Drop;
结构容器{
//线程的连接句柄
th:选项,
//当我们希望线程退出时,设置为true
停止线程:圆弧,
}
impl容器{
fn new()->Self{
//创建新实例
让mut inst=Self{
th:没有,
停止线程:Arc::new(AtomicBool::new(false)),
};
让stop_thread=inst.stop_thread.clone();
//开始一个新的线程来做一些工作
让t=thread::spawn(移动| |){
//继续工作,直到stop_线程设置为true
while!停止线程加载(排序::SeqCst){
println!(“做事…”);
线程::睡眠(时间::持续时间::from_secs(1));
}
println!(“线程已退出”);
});
inst.th=一些(t);
仪表
}
}
集装箱装卸{
fn下降(&mut自我){
self.stop_thread.store(true,Ordering::SeqCst);
如果让一些(t)=自我{
t、 join().unwrap();
}
}
}
fn main(){
设c=Container::new();
线程::睡眠(时间::持续时间::from_secs(3));
下降(c);
}
其思想是,当创建
容器
结构的新实例时,会启动一个执行某些操作的后台线程。它一直运行,直到实例被销毁,在这一点上,我需要通知线程它需要退出。在继续之前,我还需要等待线程退出

除了
drop
函数中的代码外,所有功能都运行良好。如果让一些(t)=self.th生锈,则
会使生锈不愉快。它说:

error[E0507]: cannot move out of `self.th.0` which is behind a mutable reference
  --> src/main.rs:45:26
   |
45 |         if let Some(t) = self.th {
   |                     -    ^^^^^^^ help: consider borrowing here: `&self.th`
   |                     |
   |                     data moved here
   |                     move occurs because `t` has type `JoinHandle<()>`, which does not implement the `Copy` trait
我做错了什么?

按照指定(链接方式),可以通过使用
.take()
函数解决此问题:

impl-Drop用于容器{
fn下降(&mut自我){
self.stop_thread.store(true,Ordering::SeqCst);
如果让一些(t)=自身的th.take(){
t、 join().unwrap();
}
}
}

尽管您可能想考虑在代码中等待另一个线程> Load 实现是个好主意

<代码>连接< /COD>期望移动自己,这意味着您需要线程的所有权。如果将
self.th
替换为
self.th.take()
,则它可以工作,但也将从
容器中删除它。有关详细信息,请选中
Option::take()
error[E0507]: cannot move out of `*t` which is behind a shared reference
  --> src/main.rs:46:13
   |
46 |             t.join().unwrap();
   |             ^ move occurs because `*t` has type `JoinHandle<()>`, which does not implement the `Copy` trait