\nCall .join()
or .detach()
for orderly ending, depending on what you need.
Alternatively upgrade to C++20, which introduced std::jthread
which joins instead of terminating.
Reputation: 105
I have a program where I want to run one of my classes in a separate thread with a higher priority than the rest of the program and I want it to update the GUI as it processes so I'm using std::thread
.
GUI.h
#include <thread>
class GUI
{
private:
Worker worker;
std::thread workerThread;
public:
GUI ();
~GUI ();
void runWorker ();
}
GUI.cpp
GUI::GUI ()
{
}
GUI::~GUI()
{
}
void GUI::runWorker()
{
workerThread = std::thread (&Worker::run, worker);
}
Worker.h
class Worker
{
public:
void run ();
}
Worker.cpp
void Worker::run ()
{
unsigned int numItems = 70;
for (unsigned int i = 0 ; i < numItems ; i++)
{
try
{
processItem (i);
}
catch (exception &e)
{
std::cout << "Error processing item " << i << std::endl;
break;
}
}
}
My problem is whether Worker::run
finishes cleanly or if there is an exception it will end and when I try to call the destructor for GUI it crashes in std::terminate
in std::thread
.
Is this a problem because the std::thread
no longer exists because the Worker has already finished? How can I keep the GUI destructor from calling the std::thread
destructor if Worker::run
has already finished?
Upvotes: 2
Views: 1170
Reputation: 45704
std::thread
will std::terminate()
on destruction if it manages a thread.
Call .join()
or .detach()
for orderly ending, depending on what you need.
Alternatively upgrade to C++20, which introduced std::jthread
which joins instead of terminating.
Upvotes: 4