Reputation: 2054
Today, I've seen a code like:
void Foo()
{
MyMsgStruct myMsg;
/* omission for simplicity */
/* send to update thread */
PostThreadMessage(myThreadId, myMessage, (WPARAM)myMsg, NULL);
}
What happens when Foo()
is called from the same thread as myThreadId
, i.e. from the same thread that's supposed to be the target thread? Is it a performance issue or just bad written code or both?
I believe it may affect performance since I believe it would queue the message to the thread's queue instead of just doing what it's supposed to do, therefore slowing the program a little.
Thread safety is not my concern for this question.
Upvotes: 1
Views: 3577
Reputation: 941317
Nothing very special, it just takes a while before whatever code is supposed to run will be called. Just a delay, it doesn't necessarily make your program slower. Sometimes you do it on purpose, like wanting to respond to a Windows message but doing it right away causing re-entrancy issues.
Using PostThreadMessage should however almost always be avoided. Really Bad Things happen when the thread also creates windows, almost always the case since you tend to post to the UI thread to get code to, say, update a window. Messages fall in the bit bucket whenever a modal loop is entered. Like the one that is used to resize a window. Or displays MessageBox. Always favor posting to a window instead, the message cannot get lost. Do check the return value of PostMessage().
Creating a dummy invisible window whose window procedure handles these messages is generally a good idea. You now also have a way to check if you need to post or can execute directly with SendMessage. Compare GetWindowThreadProcessId with GetCurrentThreadId.
Upvotes: 7
Reputation: 595710
The message goes into the message queue of the target thread ID, regardless of which thread is calling PostThreadMessage()
. It is perfectly valid for a thread to post messages to itself. The message will be processed when the thread pumps its message queue for new messages. Sometimes a thread really may want to have a delayed action, so a posted message is good for that. If a thread wants to do something immediately, there is no point in calling PostThreadMessage()
, just perform the operation directly. There is no equivalent to SendMessage()
for thread messages.
Upvotes: 3