title: Windows: WaitForSingleObject crashes when thread returns 0
body: <p>I am having a strange behavior: WaitForSingleObject seems to crash when I return 0 from my thread, but if I call "ExitThread(0)" then it does not.</p>
  
  <pre><code>void waitForThread(DWORD &amp;threadId)
  {
      HANDLE hThread = OpenThread(SYNCHRONIZE,
                          FALSE,
                          threadId);
  
      if (hThread == NULL) return;
  
      WaitForSingleObject(hThread, INFINITE); // Crashes here (not even returning)
      CloseHandle(hThread);
  }
  </code></pre>
  
  <p>According to the documentation:</p>
  
  <blockquote>
    <p>ExitThread is the preferred method of exiting a thread in C code. However, in C++ code, the thread is exited before any destructors can be called or any other automatic cleanup can be performed. Therefore, in C++ code, you should return from your thread function.</p>
  </blockquote>
  
  <p>This does not make sense to me. I would think that "return 0" in my function with the signature:</p>
  
  <pre><code>DWORD WINAPI foo(LPVOID arg);
  </code></pre>
  
  <p>would be fine. For completeness, the thread is created using CreateThread, as such:</p>
  
  <pre><code>    DWORD threadId;
      HANDLE pth = CreateThread(NULL, // Default security attributes
                      0, // Default stack size
                      foo, // Thread name
                      arg, // Argument to thread
                      0, // Default creation flag
                      &amp;threadId); // Returns thread ID
  </code></pre>
  
  <p>Does anyone know why the return statement would crash "WaitForSingleObject" please? I have put print statement before and after WaitForSingleObject, and one when the thread exists, and the behavior I see is: "Before WaitForSingleObject", "Thread finishes", Crash. Does anyone understand this behavior please?</p>