Std :: thread :: detach fails after destroying the original caller

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? } }; 

When the Test instance is initialized, it generates and separates std::thread , which runs in the background. When the same instance is destroyed, the stream mentioned above tries to access the active element, which was destroyed with the instance, causing a failure (and AddressSanitizer backtracking).

Is there a way to stop the dedicated thread on ~Test() ?

The design is bad. How will a thread running in the background until the caller is destroyed be spawned / processed correctly?

+7
c ++ multithreading c ++ 11 stdthread
source share
2 answers

Make the stream a member of the class and instead of detaching it in the constructor, attach it to the destructor. To stop the loop from looping, you can have a boolean inside the class that signals whether the thread should continue to work or not ( std::atomic<bool> update ).

A thread can do the following: [this] { while (update) threadUpdate(); } [this] { while (update) threadUpdate(); } .

In the destructor of your class, do update = false and call thread.join()

+12
source share

You cannot stop individual threads. That point .detach() - you no longer need to refer to the selected stream, at least to the level of C ++ defines. If you want to keep the thread descriptor, save std::thread and call .join() in the destructor.

+7
source share

All Articles