2016-08-18 121 views
0

我想运行一个线程,做这样简单的东西:终止正在运行的线程C++的std ::线程

main(){ 
    std::thread thread_pulse([=]{ 
     *this->do_adress = true; 
     std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds)); 
     *this->do_adress = false; 
     //delete this thread to avoid memory leaks 
    }); 
    //do some other stuff without waiting for the thread to terminate 
} 

我怎么保证,当线程执行完成的线程删除,并且没有内存泄漏而不等待线程在main上完成执行?

编辑:

感谢您的帮助,蒙山这个工作,因为我想

main(){ 
    std::thread ([=]{ 
     *this->do_adress = true; 
     std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds)); 
     *this->do_adress = false; 
     //delete this thread to avoid memory leaks 
    }).detach; 
    //do some other stuff without waiting for the thread to terminate 
} 
+0

'std :: thread thread_pulse(...); thread_pulse.detach();' –

回答

4

如果你想确保你退出main在那之前你返回正确的前线程完成帮助main使用

thread_pulse.join(); 

这将等待thread_pulse继续之前完成。

如果你如果线程完成,然后不在乎你可以在创建后detach它像

thread_pulse.detach(); 

。这会让程序结束而不会抛出异常。


另外,您可以建立一个存储线程包装类,当它被破坏,它会调用joindetach给你,让你不必记住。您可以使用类似Scott Myers ThreadRAII

class ThreadRAII 
{  
public:  
    ThreadRAII(std::thread&& thread): t(std::move(thread)) {} 
    ~ThreadRAII() { if (t.joinable()) t.join(); } 
private:  
    std::thread t;  
}; 

,要么修改,让你选择是否要join()detach()或只是硬编码的行为。

+0

我真的想要一个分离。谢谢,我会编辑问题供将来参考 – heczaco

+0

@heczaco没问题。乐意效劳。 – NathanOliver