开发者

correctly terminate a running thread which "works"

开发者 https://www.devze.com 2023-03-25 12:49 出处:网络
I have a thread like this: DWORD WINAPI message_loop_thread(LPVOID dummy) { MSG message; while (GetMessage(&message, NULL, 0, 0)) {

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消