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.
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:
moved your thread?friendmethod 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
workThreadis default constructed upon constructing an object ofexampleClass. A callback function is only passed, if you calldoWork(). 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 afriend. 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.