考虑以下代码:
unsigned int __stdcall func( LPVOID ) {
LRESULT result = ::PostThreadMessage( ::GetCurrentThreadId(), 0, 0, 0 );
return 0;
}
int wmain() {
_beginthreadex( NULL, 0, func, NULL, 0, NULL );
...
}
为什么::PostThreadMessage会成功?我认为它应该失败,因为那一刻不应该创建消息队列
最佳答案
因为您正在当前线程上调用 PostThreadMessage()
,所以系统能够按需创建消息队列。如果您正在调用 PostThreadMessage()
并传递调用线程以外的线程的 ID,那么如果该线程没有消息队列,它将失败。
例如,考虑以下代码变体:
unsigned int __stdcall func( LPVOID ) {
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
unsigned int threadID;
_beginthreadex( NULL, 0, func, NULL, 0, &threadID );
LRESULT result = ::PostThreadMessage( threadID, 0, 0, 0 );
DWORD error = ::GetLastError();
return 0;
}
因为我们现在正试图从主线程向工作线程发送消息,result
返回 0(即错误),而 error
是设置为 ERROR_INVALID_THREAD_ID
,如 documentation for PostThreadMessage()
所述.
If the function fails, the return value is zero. To get extended error information, call GetLastError. GetLastError returns
ERROR_INVALID_THREAD_ID
ifidThread
is not a valid thread identifier, or if the thread specified byidThread
does not have a message queue.
关于winapi - 什么时候创建消息队列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6677633/