One way communication between two threads through Events
I have two threads that communicate in the following way: Thread A posts a message in a message queue and Thread B processes that message. Thread A has to wait until Thread B processes the message.
Thread A
.........
post a message on the message开发者_开发百科 queue WaitForSingleObject (hEvent) Use the message processed information SetEvent(hEvent) .........Thread B
Process the message in the message queue
SetEvent(hEvent)
Do you see any problems with the above code? Do I need to call ResetEvent() anywhere? Is the SetEvent() call required in Thread A or Thread A should only call WaitForSingleObject() and Thread B should only call SetEvent()?
Thanks in advance
You needn't call ResetEvent
as long as the event is an AutoReset Event. This parameter is set in CreateEvent
. I think your pseudocode is OK.
A problem you will need to consider is the potential deadlock with this. If Thread A has to wait until Thread B processes the event before continuing (and your WaitForSingleObject call does not have a useful timeout value passed to it), there is a chance that Thread B will never process the event and will lock Thread A.
精彩评论