简体   繁体   中英

What can cause a joinable thread to fail when calling join

When I call joinThread I occasionally get a std::system_error throw 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, ie 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.

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 move d 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM