Reputation: 755
Consider the following code:
unsigned int __stdcall func( LPVOID ) {
LRESULT result = ::PostThreadMessage( ::GetCurrentThreadId(), 0, 0, 0 );
return 0;
}
int wmain() {
_beginthreadex( NULL, 0, func, NULL, 0, NULL );
...
}
Why does ::PostThreadMessage succeed? I think that it should fail because a message queue should not be created by that moment
Upvotes: 3
Views: 312
Reputation: 613481
Because you are calling PostThreadMessage()
on the current thread, the system is able to create the message queue on demand. If you were calling PostThreadMessage()
and passing the ID of a thread other than the calling thread, then it would fail if that thread did not have a message queue.
For example, consider the following variant of your code:
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;
}
Because we are now attempting to post the message from the main thread, to the worker thread, result
comes back as 0 (i.e. an error), and error
is set to ERROR_INVALID_THREAD_ID
as described by the 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.
Upvotes: 3