问题描述
今天,我看到了类似的代码:
Today, I've seen a code like:
void Foo()
{
MyMsgStruct myMsg;
/* omission for simplicity */
/* send to update thread */
PostThreadMessage(myThreadId, myMessage, (WPARAM)myMsg, NULL);
}
如果从与myThreadId
相同的线程中调用Foo()
,即从应为目标线程的同一线程中调用,会发生什么情况?是性能问题,还是写得不好的代码,还是两者兼而有之?
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.
推荐答案
没什么特别的,只是花了一段时间才能调用任何应该运行的代码.只是一个延迟,它并不一定会使您的程序变慢.有时,您是故意这样做的,例如希望响应Windows消息,但立即这样做会导致重新进入问题.
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.
但是几乎应该避免使用PostThreadMessage.当线程还创建窗口时,确实发生了不好的事情,几乎总是这样,因为您倾向于发布到UI线程来获取代码,例如更新窗口.每当进入模态循环时,消息就会落入位存储桶中.类似于用于调整窗口大小的窗口.或显示MessageBox.始终偏向于发布到窗口,消息不会丢失.请检查PostMessage()的返回值.
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().
创建一个虚拟的不可见窗口,其窗口过程处理这些消息通常是一个好主意.现在,您还可以检查是否需要发布或可以直接使用SendMessage执行.比较GetWindowThreadProcessId与GetCurrentThreadId.
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.
这篇关于来自目标线程的PostThreadMessage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!