\n1) Assuming that calling a message-retrieval function is not part of normal message handling.
\n2) See When can a thread receive window messages? for details on why this is the case.
Reputation: 109
What happens if I use SendMessage() from different threads to one receiver? Imagine a situation, when receiver is still processing a message from Thread1 and Thread2 sends another message (with SendMessage()). What happens in the receiver end? Does it stop execution of Message1, process Message2 and after finishing with Message2 returns to Message1 back? Or does Message2 waits for end of Message1?
Upvotes: 0
Views: 2300
Reputation: 51512
The basic rule is: The only time a thread dispatches cross-thread sent messages is, when calling a message-retrieval function (GetMessage, PeekMessage, etc.) on that thread. The message-retrieval functions first check for any cross-thread sent messages, dispatch them one after another, and then move on to retrieve a message from the thread's message queue.
This has 2 consequences:
In your particular example, the receiver will continue to handle Message1 until finished, and move on to dispatch Message2 the next time it calls a message-retrieval function.
There is one notable exception to this rule: A thread that is waiting for SendMessage to return can dispatch inbound cross-thread sent messages2). This means that there is a potential for re-entrancy. Taking your example again, suppose that the message handler for Message1 at some point calls SendMessage
, it could well be, that Message2 is dispatched before handling of Message1 continues.
To sum it up:
Upvotes: 4
Reputation: 17678
I'll assume that the question is about messages being sent to a particular window i.e. a HWND other than NULL or HWND_BROADCAST, and that the window is owned by a thread belonging to the same process .
In this case, the thread that created the target window will receive the message next time GetMessage is called with a filter that includes the given window. The sending thread will be blocked until the receiving thread actually completes processing of the message.
If, while processing the message from Thread1, the receiving thread calls GetMessage/DispatchMessage again, then any pending message (including messages possibly sent by Thread2) will be processed at that point, then control will return to processing of the message from Thread1.
From the docs for the SendMessage function:
If the specified window was created by the calling thread, the window procedure is called immediately as a subroutine. If the specified window was created by a different thread, the system switches to that thread and calls the appropriate window procedure. Messages sent between threads are processed only when the receiving thread executes message retrieval code. The sending thread is blocked until the receiving thread processes the message.
Upvotes: 1