So I have a multithreaded C++ console application in which I want to handle the console close event in order to perform cleanup.
I have something to this effect:
bool running = true;
ServerSocket* server;
std::mutex mutex;
BOOL WINAPI HandlerRoutine(DWORD)
{
running = false;
server->shutdown();
std::lock_guard<std::mutex> guard(mutex);
return TRUE;
}
int main()
{
std::lock_guard<std::mutex> guard(mutex);
SetConsoleCtrlHandler(&HandlerRoutine, TRUE);
try {
ServerSocket server(27015);
::server = &server;
while (running)
{
TCPSocket* client = server.accept(true);
}
}
catch (const ServerSocket::ServerShutdownException&)
{
return 0;
}
}
If I return from HandlerRoutine
my program gets terminated unceremoniously, so I have to wait for main()
to end.
However, after main ends I get an exception telling me a mutex was destroyed while busy, thrown from dynamic atexit destructor for 'mutex'()
. This leads me to believe that static and global variables are destroyed as soon as main
returns, leaving my handler function hanging around with invalid globals.
Is this the standard specified behaviour, and if so, any idea about how I can achieve my desired effect?