Re: when my window talks to my thread
On Tue, 15 Apr 2008 18:35:07 -0700 (PDT), alexl <alextheblade@gmail.com>
wrote:
hi,
I started my ui thread like this
theApp.m_uithread=(CMyUIThread*)AfxBeginThread(RUNTIME_CLASS(CMyUIThread));
and I have a window that talks to it like this
CMyWnd::MyFunction() {
theApp.m_uithread->PostThreadMessageW( ... );
}
but when I lock like this
CMyWnd::MyFunction() {
theApp.m_uithread->PostThreadMessageW( ... );
m_myCEvent = new CEvent();
m_myCEvent->Lock();
}
it gets in a deadlock and the function in my ui thread that I called
via theApp.m_uithread->PostThreadMessageW stops running.
See the necessary conditions for deadlock here:
http://en.wikipedia.org/wiki/Deadlock
You've shown half the necessary conditions. The other half lies in the
target thread, in code you haven't shown.
A couple of things:
1. PostThreadMessage is problematic if the target thread creates windows,
directly or indirectly. For more, see:
PRB: PostThreadMessage Messages Lost When Posted to UI Thread
http://support.microsoft.com/kb/183116
2. I suppose the target thread is also using m_myCEvent. If so, you'd
appear to have a race condition, because the target thread may try to
access it before the posting thread creates it. And why are you creating it
dynamically?
Is what I am calling a ui thread really a ui thread?
If it runs a message loop, it's an "UI thread". The form of AfxBeginThread
you're using indicates you're creating an UI thread.
Am I doing it
right? Is the window thread and the ui thread separate? thx
A window belongs to whichever thread created it. That is, if a window is
created by a thread X, only thread X can process messages for that window.
There are three ways for a window to process a message:
1. PostMessage posts a message to the owning thread's message queue, which
the thread later retrieves and dispatches.
2. Code running in the owning thread calls SendMessage on the window, which
amounts to an ordinary function call (intra-thread SendMessage).
3. Code running in a different thread calls SendMessage on the window
(inter-thread SendMessage). This causes the sending thread to block, and
the message isn't processed until the thread that owns the window calls a
function such as GetMessage, WaitMessage, and yes, even SendMessage, which
are considered "safe" points to perform a context switch so that the owning
thread can process the sent message. Only after the target thread returns
from its window procedure or calls ReplyMessage does the sender thread
resume execution. Careless use of inter-thread SendMessage can easily
result in deadlocks, but as you are using PostThreadMessage, it doesn't
apply to what you've shown.
--
Doug Harrison
Visual C++ MVP