1

I have a thread like this:

DWORD WINAPI message_loop_thread(LPVOID dummy) {
        MSG message;
        while (GetMessage(&message, NULL, 0, 0)) {
                TranslateMessage(&message);
                DispatchMessage(&message);
        }
}

And i start it with CreateThread:

DWORD thread_id;
CreateThread(0, 0, message_loop_thread, 0, 0, &thread_id);

This seems to work, but how can i correctly close this thread? Normally the thread is waiting for GetMessage so the thread is blocked i think.

Is there a good way to do this? I tried TerminateThread, but this hangs, and i think it's not a good solution to stop the thread.

Has someone an idea?

best regards Benj Meier

Stefan Hasler
  • 115
  • 1
  • 2
  • 5
  • Do not use `CreateThread()` unless you are aware of what it does *not* do. `CreateThread()` does not initialize the runtime properly, nor does it set up CRT finalization hooks to execute when the thread dies. See a discussion here: http://stackoverflow.com/questions/331536/windows-threading-beginthread-vs-beginthreadex-vs-createthread-c – Jörgen Sigvardsson Aug 02 '11 at 12:55

1 Answers1

3

The proper way is to post WM_QUIT to thread_id. You use PostThreadMessage() for this. In response, GetMessage returns 0, the while loop exits, and the function exits (incorrectly, you're missing a return statement). When the toplevel function of a thread exits, the thread ends.

MSalters
  • 159,923
  • 8
  • 140
  • 320