c++ - 终止正在运行的线程 c++ std::thread

标签 c++ multithreading

我想运行一个线程来做一些像这样简单的事情:

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();

创建后。这将使程序结束而不会抛出异常。


或者,您可以构建一个包装器类来存储线程,当它被销毁时,它将为您调用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(),或者只是对行为进行硬编码。

关于c++ - 终止正在运行的线程 c++ std::thread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39020986/

相关文章:

c++ - 我可以在异步 io_machine 中使用阻塞 I/O 吗?

c++ - C++ 中的并行循环

c++ - 在 Visual Studio 2010 中测量 C++ 项目性能的问题

c# - 可读性 a=b=c 或 a=c; b=c;?

java - 长时间运行的 HTTP 请求和线程同步

java - 为什么并发线程限制没有按预期工作?

swift - CoreData 多线程正在生成随机崩溃

c++ - boost 多边形丢弃输入多边形

Python 3.4并发.futures.Executor不提供暂停和恢复线程的控制

java - 线程中的异常