Synchronization problem

Synchronization problem

Post by mojzis.ras » Mon, 10 Jan 2005 18:23:02


I have following problem with threads synchronization (in Win2000)

The main thread (let's say thread A) creates two separate threads
(thread B and C), which implements window registration and creation.
In threads B and C then runs the window message looping. These windows
(running in threads B and C) are used for treating SOCKETs messages
(FD_READ, FD_CONNECT etc). Of course, sockets are put in asynchornous

Then, in main thread A I do following ...

HANDLE syncObject = CreateEvent(NULL, TRUE, FALSE, NULL);
PostMessage(hSocketWndThreadB, WM_SEND_PACKAGE, (WPARAM)packagePtr,
WaitForSingleObject(syncObject, INFINITE);

Event syncObject will be signaled, when an answer from server will
arrive so I want to wait for server reply (or error of course)
(calling of SetEvent(syncObject) is implemented in thread B, after the
server reply is received).

Everything looks fine, message WM_SEND_PACKAGE is sent to appropriate
window and package is sent (socket method "send" returns the size of
package). The problem is with calling the WaitForSingleObject
function. When I do this, all threads look to be blocked (ie. not only
thread A, but also thread B and C).

Why ? Can U please explain me, why threads B and C are blocked too ?

To test, that threads B and C are blocked I used following method:
I created timers on windows, which are implemented in thread B and C
in thread B I called SetTimer(hSocketWndThreadB, 1, 1000, NULL) and in
thread C I called SetTimer(hSocketWndThreadC, 2, 1500, NULL). When
message WM_TIMER has arrived, i called MessageBeep(...). I noticed,
that after WaitForSingleObject in thread A system stoped sending of
WM_TIMER messages that it looks like threads B and C are blocked too.

Thank you for any help or explanaition of this synchronization

Rastislav Mojzis.

Synchronization problem

Post by Scott McPh » Mon, 10 Jan 2005 22:35:41

When they are all blocked you can break in with a de *** and examine
each thread to see exactly where it has blocked.

A frequent cause of this is accessing a window from a thread that did
not create it. For example, SendMessage will block until the thread
that created the window processes the messsage. If that owning thread
is in WaitForSingleObject then both sender and receiver deadlock.

Scott McPhillips [VC++ MVP]


Synchronization problem

Post by jeff » Thu, 13 Jan 2005 04:18:55

Given that you have no control over who sends you messages, you
should never use WaitForSingleObject in thread with a message loop.
Use MsgWaitForMultipleObjects or MsgWaitForMultipleObjectsEx
and make sure you use (at the minimum) the QS_SENDMESSAGE flag
to ensure that messages sent with SendMessage are received.

(Even if this isn't the source of your problem, you should fix this!)

-- jeff