在析构函数

时间:2016-10-16 11:33:07

标签: c++ multithreading c++11

在一个项目中,我们在包装类中创建多个状态机。每个包装器都在它自己的线程中运行。当作业完成时,正在调用包装类析构函数,在那里我们想要停止该线程。

虽然如果我们使用thread.join(),我们会遇到死锁(因为它试图加入自己)。我们可以以某种方式发出另一个线程的信号,但这看起来有点乱。

在对象销毁时,有没有办法正确终止运行类的线程?

1 个答案:

答案 0 :(得分:0)

thread.join()不会停止某个帖子。它等待线程完成然后返回。为了停止一个线程,你必须有一些方法告诉线程停止,并且线程必须检查是否有时间停止。一种方法是使用原子布尔:

class my_thread {
public:
    my_thread() : done(false) { }
    ~my_thread() { done = true; thr.join(); }
    void run() { thread th(&my_thread::do_it, this); swap(th, thr); }
private:
    void do_it() { while (!done) { /* ... */ } }
    std::thread thr;
    std::atomic<bool> done;
};

这是我的头脑;未编译,未经测试。