Pages

Friday, 5 November 2021

Windows Tech Series: A background thread with message queue

 In Windows, a thread doesn't have its own message queue until it firstly calls a GUI32/GDI32 API.

According to MSDN, the background thread should call PeekMessage() to trigger the creation of its message queue.

Below is my example code. Please be aware of the difference between Thread ID and Thread Handle.

#include <Windows.h>
#include <stdio.h>
#include <process.h>

void ThreadProc(void* pParam)
{
printf("I am a thread.\n");
MSG msg;
HANDLE eventMessageQueueReady = *((HANDLE*)pParam);
// prepare message quque
PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
SetEvent(eventMessageQueueReady);
while (GetMessage(&msg, NULL, 0, 0)) {
printf("Got message %d\n", msg.message);
switch (msg.message)
{
case WM_USER + 1:
break;
case WM_USER + 100:
PostQuitMessage(0);
break;
default:
break;
}
}
printf("exit thread\n");
_endthread();
}

int main(int argc, char** argv)
{
HANDLE eventMessageQueueReady = CreateEvent(NULL, FALSE, FALSE, NULL);
if (eventMessageQueueReady == NULL) {
exit(1);
}
HANDLE hThread = _beginthread(ThreadProc, 0, &eventMessageQueueReady);
DWORD idThread = GetThreadId(hThread);
// wait until the message queue is ready in child thread
WaitForSingleObject(eventMessageQueueReady, INFINITE);

PostThreadMessage(idThread, WM_USER, 0, 0);
PostThreadMessage(idThread, WM_USER+100, 0, 0);
Sleep(10000);
return 0;
}

No comments:

Post a Comment