3

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.

void waitForThread(DWORD &threadId)
{
    HANDLE hThread = OpenThread(SYNCHRONIZE,
                        FALSE,
                        threadId);

    if (hThread == NULL) return;

    WaitForSingleObject(hThread, INFINITE); // Crashes here (not even returning)
    CloseHandle(hThread);
}

According to the documentation:

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.

This does not make sense to me. I would think that "return 0" in my function with the signature:

DWORD WINAPI foo(LPVOID arg);

would be fine. For completeness, the thread is created using CreateThread, as such:

    DWORD threadId;
    HANDLE pth = CreateThread(NULL, // Default security attributes
                    0, // Default stack size
                    foo, // Thread name
                    arg, // Argument to thread
                    0, // Default creation flag
                    &threadId); // Returns thread ID

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?

user1777907
  • 1,355
  • 4
  • 12
  • 28
  • 1
    May be, its not the `WaitForSingleObject()` which is crashing, it would be something else. – raj raj Jul 03 '13 at 04:10
  • I ran it in the debugger and it seems to be WaitForSingleObject() again. When commenting out WaitForSingleObject(), it also doesn't crash. – user1777907 Jul 03 '13 at 20:02

0 Answers0