0

I have a ThreadPool class (simplified version here) in a multi-platform library which can be compiled either as static or dynamic. I create threads on first use, and clean them up in the destructor by submitting dummy jobs.

It works well except combination of Windows+DLL, where the threads are terminated by the OS before the class' destructor is invoked in library's DllMain function.

Is this a bug in Visual Studio? There was something similar already. If not, is there a more elegant solution than:

  bool waitForThreads = true;
#if defined(WIN32) && !defined(ITK_STATIC)
  DWORD dwWaitResult = WaitForSingleObject(m_Threads[0], 1);
  if (dwWaitResult == WAIT_OBJECT_0) //thread has finished
  {
      //thread terminated by CRT
      waitForThreads = false;
  }
#endif

  if (waitForThreads) //add dummy jobs for clean thread exit
  {...}
Dženan
  • 3,329
  • 3
  • 31
  • 44
  • As a general rule, your system needs to be explicitly started and shut down and not exist at "global" or "static" scope if it has threads in it. Thread before or after main are a bad plan. – Yakk - Adam Nevraumont Nov 20 '17 at 20:33
  • 1
    Here's one article that provides some notes and links that explain your situation. It's not a bug in Visual Studio unfortunately, it's a Windows design behavior. [Creating a thread in DllMain?](https://stackoverflow.com/q/1688290/6610379) – Phil Brubaker Nov 20 '17 at 20:43

0 Answers0