Re: Threads, Message Pump and Sync
On Dec 7, 2:21 pm, MariusVE <pris...@gmail.com> wrote:
I have modified my code because I don't think it was implemented quite
right. At this point, I'm pretty sure the exiting mechanism is correct
since I post a "last message" after sending the CString's.
When the last message is received, I set a manually-reset event to
inform the worker thread that it can inform the deleting worker thread
that it can start its deallocations. After I go through the list, I
post a message to close the application.
However, even so, I still have the memory leaks. To my amazement, I
discovered that although I called "PostMessage" 15 000 times, I only
got ~ 10 500 calls for my message handler.
Therefore, I wrote a small test program and this is what I have
discovered:
Similarly as before, from the worker thread, I have a for loop:
for (int i = 0; i <= 15000; ++i)
PostMessage(UserMessage, 0, 0);
I confirmed via a TRACE statement that indeed, I have sent 15 000
messages.
However, the UserMessage handler only gets called ~10 500 times. This
value fluctuates so this number is really meaningless. What's
important is that some messages are somehow "lost" on their way to the
UI thread.
I have tried to lower the worker thread's priority to LOWEST and I
still have this problem.
Note: This is a bare-bones new MFC dialog based project. Nothing funny
going on; I just have a worker thread that posts messages to the UI;
nothing else, no other variables, nothing.
What's strange is that if, and this is going to sound annoying to a
lot of you, I put a "Sleep(some-meaningless-value-in-a-non-realtime-
operating-system)" :) , the UserMessage's message handle gets called
the correct number of times (i.e, 15 000 times) !
Check return value from PostMessage. You saturated receiving thread's
message queue (limit is 10000 messages, and is configurable through
registry, but I won't tell you how, because this parameter is not
yours to change).
You must not do p = new whatever; PostMessage(..., p, ...);
You must do:
p = new whatever;
if (!PostMessage(..., p, ...))
{
// Problem. Solutions: wait and retry, delete p and signal error,
// change post frequency so that receiving thread can empty the
queue.
}
IOW, you just found out that windows message queue is not general-
purpose message queue (which is kinda obvious from what it does and
how).
Goran.