What can cause a joinable thread to fail when calling join

5.4k Views Asked by At

When I call joinThread I occasionally get an std::system_error thrown of with "invalid argument" at the join call. The error appears to only show up when I compile with gcc, and it is not consistently reproducible, i.e. it occasionally occurs and not predictably. Does anyone know what could cause such an error?

Below is a reduced version of my code.

class exampleClass
{
   public:
   exampleClass()
   {
   }
   
   ~exampleClass()
   {
      joinThread();
   }

   void doWork()
   {
       joinThread();
       workThread = std::thread(&exampleClass::threadFunction, this);
   }

   void joinThread()
   {
      if(workThread.joinable()) workThread.join();
   }

   protected:
   void threadFunction()
   {
      std::cout << "Do something that requires time..." << std::endl
   }

   std::thread       workThread;
}

Any help would be greatly appreciated.

1

There are 1 best solutions below

0
Zacryon On

Since you did not provide an example, where this error occurs, I can only speak from my own experience. There are some things you should consider, in order to avoid such an error:

  • Is your thread just default constructed, resp. did you initialize it with a valid callback function?
  • Is your thread detached?
  • Have you moved your thread?
  • Is the thread trying to access an already reserved resource? Think about possible deadlock sources! Maybe you got stuck somewhere. (But afaik the thread should still be joinable anyway.)
  • Does a friend method or class try to access/use/join the thread?

I recently forgot to pass a function to a thread, which I had default constructed in order to use it later. This happened due to a conditional initialization procedure. So regarding your example class above: Your workThread is default constructed upon constructing an object of exampleClass. A callback function is only passed, if you call doWork(). You have made sure that the thread is only joined, if it is in a joinable state. Upon destruction of your object this is also guaranteed. Thus, the most likely reason I can think of, why this might fail, is if you have somewhere a friend. You haven't put that in your example though, but maybe you neglected this, because you wanted to present a reduced form.

Maybe also a look here: http://cppatomic.blogspot.com/2018/05/modern-effective-c-make-stdthread.html might help.