我想运行一个线程来做一些像这样简单的事情:
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
}
最佳答案
如果你想确保线程在退出 main
之前完成,那么在你从 main
返回之前使用
thread_pulse.join();
这将等待 thread_pulse
在继续之前完成。
如果您不关心线程是否完成,那么您可以分离
它
thread_pulse.detach();
创建后。这将使程序结束而不会抛出异常。
或者,您可以构建一个包装器类来存储线程,当它被销毁时,它将为您调用join
或detach
,因此您不必记住。你可以使用类似 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()
,或者只是对行为进行硬编码。
关于c++ - 终止正在运行的线程 c++ std::thread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39020986/