Nathaniel J. Smith
Nathaniel J. Smith

Reputation: 12782

Does closing an event object cause threads waiting on that object to wake up?

Suppose I have a Windows event object, e.g. from calling CreateEvent.

Thread A is blocked in WaitForSingleObject(event_handle).

Thread B calls CloseHandle(event_handle).

Question 1: What happens to thread A?

Question 2: Does it make a difference if Thread A is blocked in WaitForMultipleObjects? What does WaitForMultipleObjects return?

Upvotes: 8

Views: 483

Answers (1)

Nathaniel J. Smith
Nathaniel J. Smith

Reputation: 12782

From experimentation, it seems that WaitForSingleObject does not wake up if the handle is closed, i.e. thread A keeps waiting. I haven't checked, but I assume WaitForMultipleObjects is the same.

I suspect what's going on is that event objects inside the kernel are reference counted. CloseHandle drops a reference, but it doesn't necessarily destroy the underlying object. (For example, if multiple processes hold handles to the same object, the object isn't destroyed until all of the processes call CloseHandle.) And WaitForSingleObject also takes a reference to the object it waits for. Of course, I don't have the Windows source code so I can't confirm this for certain.

Upvotes: 2

Related Questions