// JP opened flex table

Click to See Complete Forum and Search --> : Question on PostThreadMessage()


cyberninja
March 9th, 2004, 05:01 PM
Question on PostThreadMessage()
When using PostThreadMessage(), I encounter a problem and do not know whether it is a bug or not.

Scenario:

Process 1:
1-1) create thread 1 to wait for WM_USER_TESTRESPONSE message
1-2) post WM_USER_TESTREQUEST message to thread 2.

Process 2:
2-1) create thread 2 to wait for WM_USER_TESTREQUEST message,
2-2) if WM_USER_TESTREQUEST is received,
2-3) post WM_USER_TESTRESPONSE to thread 1.

In testing, thread 2 can always receive WM_USER_TESTREQUEST, but when 2-3) happens, PostThreadMessage returns fail (Invalid thread id) and thread 1 will never receive it.

However, if I insert "Sleep(100)" between 2-2) and 2-3), PostThreadMessage will succeed and thread 1 will receive the response.

Is this an expected behaviour for PostThreadMessage()? If so, should I retry several times if PostThreadMessage() returns fail?

Thanks

cyberninja

Andreas Masur
March 9th, 2004, 05:08 PM
From MSDN:

The thread to which the message is posted must have created a message queue, or else the call to PostThreadMessage fails. Use one of the following methods to handle this situation:

Call PostThreadMessage. If it fails, call the Sleep function and call PostThreadMessage again. Repeat until PostThreadMessage succeeds.

Create an event object, then create the thread. Use the WaitForSingleObject function to wait for the event to be set to the signaled state before calling PostThreadMessage. In the thread to which the message will be posted, call PeekMessage as shown here to force the system to create the message queue.

PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE)

Set the event, to indicate that the thread is ready to receive posted messages.

cyberninja
March 9th, 2004, 05:19 PM
This is really helpful. I tried to search in MSDN but cannot find this doc - maybe there is too many articles.

Andreas Masur
March 9th, 2004, 05:34 PM
'PostThreadMessage()' (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/WinUI/WindowsUserInterface/Windowing/MessagesandMessageQueues/MessagesandMessageQueuesReference/MessagesandMessageQueuesFunctions/PostThreadMessage.asp)

//JP added flex table