Thread termination on DLL unload
I am trying to write a DLL plugin for third party software. In a plug-in, I create a thread in an init function that is called by the hosting program. However, there is no shutdown procedure where I can terminate the thread correctly. I tried this code:
DLL_EXPORT void InitFunction() // is called by the host application
{
myThread = std::move(std::thread{myThreadFunction});
}
bool WINAPI DllMain( HINSTANCE hDll, DWORD fdwReason, LPVOID lpvReserved )
{
switch (fdwReason)
{
case DLL_PROCESS_ATTACH:
{
DisableThreadLibraryCalls(hDll);
} break;
case DLL_PROCESS_DETACH:
{
IsRunning.store(false); // tell the thread it time to terminate;
if(myThread.joinable())
myThread.join();
}break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
}
return true;
}
I know this won't work because windows will call DllMain when the thread ends, but DllMain is still running and hence there will be a dead end. I tried to use DisableThreadLibraryCalls()
in different places in the Dll but that didn't work either. So how can I terminate the threads in my DLL correctly?
+3
source to share
No one has answered this question yet
See similar questions:
or similar: