如何在drop函数中加入线程?

时间:2017-03-14 15:30:19

标签: rust

我希望在结构“消失”后停止一个线程:

use std::thread;

struct Foo {
    handle: thread::JoinHandle<()>,
}

impl Drop for Foo {
    fn drop(&mut self) {
        println!("we drop data");
        self.handle.join();
    }
}

fn main() {
    let handle = thread::spawn(|| println!("hi from thread"));
    let _ = Foo { handle: handle };
}

但它没有编译:

error[E0509]: cannot move out of type `Foo`, which implements the `Drop` trait
  --> src/main.rs:10:9
   |
10 |         self.handle.join();
   |         ^^^^^^^^^^^ cannot move out of here

这是因为join需要self,而不是&mut self。如何在drop方法中加入此主题?

0 个答案:

没有答案