title: Terminating thread on DLL unload
body: <p>I'm trying to write a DLL plug-in for a third-party software.In the plug in i'm creating a thread in an initialization function which is called by the hosting program. However, there is no shutdown routine in which I could properly terminate the thread. I'm tried this code:</p>
  
  <pre><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's time to terminate;
          if(myThread.joinable())
              myThread.join();
      }break;
      case DLL_THREAD_ATTACH:
          break;
      case DLL_THREAD_DETACH:
          break;
      }
      return true;
  }
  </code></pre>
  
  <p>I know this won't work, because windows would call DllMain upon thread termintation, but the DllMain is still running and therefore would deadlock. I tried using <code>DisableThreadLibraryCalls()</code> in different places in the Dll, but that didn't work either. So, How can I terminate the threads in my DLL properly?</p>