Re: Thread execution
On Thu, 25 May 2006 07:48:09 -0400, David Wilkinson <no-reply@effisols.com>
wrote:
I must say I am truly shocked by this revelation, as it appears to have
the potential to undermine the great advantage of using SendMessage()
between threads: data integrity. That is, I always thought that you
could safely pass stack-based variables in SendMessage() because they
could not be changed (by the sending thread itself) until the call returned.
The intent is to carry over the behavior of the normal, single-threaded
case, in which window procedures are (heavily) reentrant. For example, it's
common for a child window to send a notification message to its parent, and
for the parent to send messages to the child while processing the
notification. The big difference in the MT case is that multiple threads
can hammer the sender while it's sitting in SendMessage.
I use a system with a "window-less UI thread" where the main GUI thread
uses PostThreadMessage() to request tasks of the secondary thread, and
the secondary thread uses SendMessage() to return the results. Despite
widespread criticism of using SendMessage(), I believe this is a valid
scheme, and one that is not affected by this revelation.
As long as the target thread is designed to regularly and promptly process
messages, I agree interthread SendMessage has its uses.
But I am still disturbed by this news.
It is pretty shocking. :)
In fact this feature seems to
have great potential for making a badly written program operate
"incorrectly", where otherwise it would exhibit a symptom of trouble by
locking up.
There is one gotcha I think should be noted, and it concerns PeekMessage,
which will dispatch pending interthread sent messages unless the PM_QS_xxx
flags are used and PM_QS_SENDMESSAGE is omitted. While it's forgivable to
assume PeekMessage does not and cannot process any messages, it's
nevertheless wrong, and you have to take special measures to prevent it
from doing so.
For reference, here's a link to Raymond's blog entry on this:
When can a thread receive window messages?
http://blogs.msdn.com/oldnewthing/archive/2004/06/08/150929.aspx
--
Doug Harrison
Visual C++ MVP