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
Because you are calling
PostThreadMessage()on the current thread, the system is able to create the message queue on demand. If you were callingPostThreadMessage()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:
Because we are now attempting to post the message from the main thread, to the worker thread,
resultcomes back as 0 (i.e. an error), anderroris set toERROR_INVALID_THREAD_IDas described by the documentation forPostThreadMessage().