In our study of the case of the invalid handle error when a handle is closed while a thread is waiting on it, Frederic Benoit described a scenario in which a handle was duplicated and given to another thread. That other thread would operate on the handle and then close it. All of this while the main thread was waiting on the original handle. Is it legal to close a duplicate of a handle that another thread is waiting on?
Yes, this is legal.
The prohibition is against closing a handle while another thread is waiting on that handle. It’s a case of destroying something while it is in use. More generally, you can’t close a handle while another thread is reading from that handle, writing to that handle, using that handle to modify a process or thread’s priority, signaling that handle, whatever.
But if one thread is waiting on the original handle and another thread closes a duplicate, that is not the same handle, so you didn’t break the rule. In fact, closing a duplicate while another thread is waiting on the original is not an uncommon scenario.
Consider this: Suppose there is a helper object whose job it is to set an event handle when something has completed. For example, maybe it’s something similar to ID3D12Fence::SetEventOnCompletion. When you give it the event handle, the object has to duplicate the handle to ensure that it can still get the job done even if the caller later closes the handle. Eventually, the thing completes, and the object calls SetEvent() with the duplicated handle and then closes the duplicate.
Meanwhile, your main thread has done a WaitForMultipleObjects to wait a block of signals.
There is nothing wrong with the helper object closing its private copy of the handle. The point is it didn’t close your copy of the handle, which means that the handle being waited on is not closed while the wait is in progress.
The post Can I close a duplicate handle while I’m waiting on the original? appeared first on The Old New Thing.
From The Old New Thing via this RSS feed