Yes, your deduction is correct. Seems like the best option would be to unregister your handler and then wait for it to finish before returning from main(). But if that's not an option for whatever reason, something else you could do is to wrap all your globals in a struct:
struct Globals
{
bool running;
ServerSocket* server;
std::mutex mutex;
};
Have a single, global shared_ptr
to an instance of that struct:
std::shared_ptr<Globals> globals = std::make_shared<Globals>();
Make a copy of the shared_ptr
in your handler:
BOOL WINAPI HandlerRoutine(DWORD)
{
std::shared_ptr<Globals> myGlobals = globals;
...
}
And rely exclusively on myGlobals
within the handler (there is no guarantee that the globals
pointer itself will remain valid for the entire lifetime of the thread). That way everything is kept alive until everyone is done with it.
This assumes, of course, that globals
is still valid when HandlerRoutine
begins. If that's not the case (i.e. if the system can call the handler after main returns but before the process ends), then I'll delete this answer.