原始调用者被销毁后,std :: thread :: detach导致崩溃

Vit*_*meo 7 c++ multithreading detach c++11 stdthread

struct Test {
    bool active{true};

    void threadedUpdate() {
        std::this_thread::sleep_for(std::chrono::milliseconds(1));
        if(!active) // crashes here after Test instance is destroyed
            return; 
    }

    Test() { 
        std::thread([this]{ while(true) threadedUpdate(); }).detach();
    }

    ~Test() { 
        // somehow stop the detached thread?
    } 
};
Run Code Online (Sandbox Code Playgroud)

Test初始化实例时,它会生成并分离std::thread在后台运行的实例.当同一个实例被销毁时,前面提到的线程试图访问该active成员,该成员与实例一起被销毁,导致崩溃(和一个AddressSanitizer回溯).

有没有办法停止分离的线程~Test()

设计很糟糕.如果正确生成/处理在调用者被销毁之前,如何在后台运行线程?

Moh*_*oun 12

使该线程成为该类的成员,而不是在构造函数中将其分离,将其连接到析构函数中.要阻止线程循环,可以在类中包含一个布尔值,表示线程是否应该继续运行(std::atomic<bool> update).

线程可以执行这个:[this] { while (update) threadUpdate(); }.

在你的类的析构函数中,执行update = false并调用thread.join()


小智 7

你无法阻止分离的线程.这就是.detach()- 你不再有任何方法可以引用分离的线程,至少就C++标准而言.如果要保留线程的句柄std::thread,请.join()在析构函数中存储和调用.