Joining a thread in a method that takes `&mut self` (like drop) results in “cannot move out of borrowed content”

后端 未结 4 2041
梦如初夏
梦如初夏 2020-12-19 06:21

I want to create a thread inside of the new method and stop it after the struct is destroyed:

use std::thread;

struct Foo {
    handle: thread:         


        
4条回答
  •  情歌与酒
    2020-12-19 07:08

    If you don't mind unsafe code, then here's something you could do (please look at Matthieus answer why this can be a bad idea).

    struct Foo {
        handle: ManuallyDrop>,
    }
    
    impl Drop for Foo {
        fn drop(&mut self) {
            unsafe {
                let _ = ManuallyDrop::take(&mut self.handle).join();
            }
        }
    }
    

提交回复
热议问题