mardi 30 mars 2021

std::thread member object crashes on destruction in terminate

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?

Aucun commentaire:

Enregistrer un commentaire