Question on PostThreadMessage()

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
[965 byte] By [cyberninja] at [2007-11-18 17:41:42]
# 1 Re: Question on PostThreadMessage()
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.
Andreas Masur at 2007-11-9 13:55:59 >
# 2 Re: Question on PostThreadMessage()
This is really helpful. I tried to search in MSDN but cannot find this doc - maybe there is too many articles.
cyberninja at 2007-11-9 13:57:00 >
# 3 Re: Question on PostThreadMessage()
'PostThreadMessage()' ( http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/WinUI/WindowsUserInterface/Windowing/MessagesandMessageQueues/MessagesandMessageQueuesReference/MessagesandMessageQueuesFunctions/PostThreadMessage.asp)
Andreas Masur at 2007-11-9 13:57:59 >