I am creating two different threads which start running when an object gets created.
Is it ok to join these threads inside the destructor then as below?. Hence, wait for the threads to complete before fully destructing the object.
If the threads never terminate, then the object will never fully destruct when it is going out of scope and the main function will never return as in the case below.
Is this a problem, and is there a better recommended way to do this? Thanks.
MyClass::MyClass()
{
// t1, t2 are private member variables
t1 = thread(&MyClass::producer, this);
t2 = thread(&MyClass::consumer, this);
}
MyClass::~MyClass()
{
//Join threads
if (t1.joinable())
{
t1.join();
}
if (t2.joinable())
{
t2.join();
}
}
int main()
{
MyClass mc;
}