Call to std::thread::join() in the destructor of a global variable
-
I have the following code and when running it stays blocked on the join(). So, is it possible to call std::thread::join() in the destructor of a global variable?
void MyTimerFunction();
class MyGlobal
{
public:
std::atomic<bool> m_Flag;
std::thread m_GlobalThread;MyGlobal() { m\_Flag = true; m\_GlobalThread = std::thread(MyTimerFunction); } ~MyGlobal() { m\_Flag = false; if (m\_GlobalThread.joinable()) m\_GlobalThread.join(); std::cout << "MyGlobal destroyed" << std::endl; }
};
MyGlobal Test;
void MyTimerFunction()
{
do
{
std::this_thread::sleep_for(std::chrono::seconds{10});
if (!Test.m_Flag)
break;std::cout << "New tick" << std::endl; } while (true); std::cout << "Exit MyTimerFunction" << std::endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
std::cout << "Main thread sleeping..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds{15});
std::cout << "Main thread awaking..." << std::endl;std::cout << "Main thread returning..." << std::endl; return 0;
}
-
I have the following code and when running it stays blocked on the join(). So, is it possible to call std::thread::join() in the destructor of a global variable?
void MyTimerFunction();
class MyGlobal
{
public:
std::atomic<bool> m_Flag;
std::thread m_GlobalThread;MyGlobal() { m\_Flag = true; m\_GlobalThread = std::thread(MyTimerFunction); } ~MyGlobal() { m\_Flag = false; if (m\_GlobalThread.joinable()) m\_GlobalThread.join(); std::cout << "MyGlobal destroyed" << std::endl; }
};
MyGlobal Test;
void MyTimerFunction()
{
do
{
std::this_thread::sleep_for(std::chrono::seconds{10});
if (!Test.m_Flag)
break;std::cout << "New tick" << std::endl; } while (true); std::cout << "Exit MyTimerFunction" << std::endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
std::cout << "Main thread sleeping..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds{15});
std::cout << "Main thread awaking..." << std::endl;std::cout << "Main thread returning..." << std::endl; return 0;
}
-
Quote:
it stays blocked on the join()
That's the correct behaviour: a never-ending thread won't join.
-
Not exactly, the destructor of the global variable sets an atomic to tell the thread to exit.
-
Yes, you are right, my bad, I've overlooked it. Have you already read this one: "function static variable destructor and thread"[^]?
-
Yeh, it seems to be the same thing. I checked under Linux with GCC and it works. On my point of view, Visual C++ runtime after exiting the main() destroys all the threads then all the global variables, instead of the opposite.