This is a mirror of official site: http://jasper-net.blogspot.com/

PostThreadMessage Demystified

| Monday, July 18, 2011
Introduction

Demystifying the use of much unused and highly advantageous api available for multithreading !

Using the code

For years working in multithread environment, I always wonder what the use of PostThreadMessage?, could it can be utilized in worker thread (though I used same in UI thread derived from CWinThread). I am sure every API provided have something for use, otherwise MS programmers are not stupid to provide something which is not working as part of API library. So I created a test program and when playing with worker thread, I provided a message loop inside it with HWND parameter is passed as NULL:-

MSG msg;
while(GetMessage(&msg,0,0,0))
{
    DispatchMessage(&msg);
}

This means that getmessage can gather message for current thread whether it is thread message or window message. Here is extract from MSDN

“If hWnd is NULL, GetMessage retrieves messages for any window that belongs to the current thread, and any messages on the current thread's message queue whose hwnd value is NULL (see the MSG structure). Therefore if hWnd is NULL, both window messages and thread messages are processed”

Now I added a message handler inside message loop which would wait for say thread message (WM_APP+1) to perform some action, otherwise it with continue with it work. Our fully loaded thread function would look something like this:-

DWORD threadProc(LPVOID lParam)
{

    MSG msg;
    while(GetMessage(&msg,0,0,0))
    {
        if(msg.message == WM_APP+1)
        {
            MessageBoxA(NULL,"Hello","From Thread",MB_OK);
        }
        DispatchMessage(&msg);
    }


Read more: Codeproject
QR: posthreadmessage.aspx

Posted via email from Jasper-net

0 comments: