开发者

CloseHandle confusion - Must I call CloseHandle on multiple "copies" of a handle?

I have some (more) questions about calling CloseHandle.

So, the SO citizens have spoken, and you must always close a handle.

Question 1

I've written the following code snippet in a destructor:

HANDLE handles[] = { m_hGrabberThread, m_hCtrlThread, m_hErrDispatchThread  };
int nNumHandles = sizeof(handles) / sizeof(handles[0]);

for( int n = 0; n < nNumHandles; n ++ )
    CloseHandle( handles[n] );

Is the above code valid, or must I call CloseHandle() on each handle member variable individually?

e.g.

if( m_hCtrlThread != INVALID_HANDLE_VALUE )
    CloseHandle( m_hCtrlThread );

I suppose that this question is linked (vaguely) to question 2...

Question 2

I have a class that creates an event handle:

HANDLE h开发者_Go百科EventAbortProgram = CreateEvent( NULL, TRUE, FALSE, NULL );

This handle is shared among other threads in other objects.

By sharing the handle, I mean:

objectB.m_hEventAbort = objectA.m_hEventAbort;

Each object's threads will then do something like:

while( WaitForSingleObject(m_hEventAbort, 0) == WAIT_TIMEOUT ) {...}

When the event is signaled, all threads will exit.

My question is: must I call CloseHandle on each copy of the handle, or just once in my main "parent" object?

I suppose that I'm asking - are handles reference counted when they're copied?

I know that a handle is only a typedef for a void*, so my instinct says no, I only need to call it once per handle.


To Question 2: The number of calls to CloseHandle should balance the number of calls to handle creation functions. If you simply assign a handle to another HANDLE variable, you have not created a new handle - the two handles have the same value. You can share the handle value as much as you want, but only one object must ultimately close the handle.

If you can't guarantee the destruction order of the objects sharing a handle; you can use DuplicateHandle to make additional handles from an existing handle. Each additional handle created would need to be closed, and the underlying object the handles reference would only be released when all the handles were closed.


Answer 1 Your above code is valid. But I suggest You to check wether the handle "under" the current index is a valid handle.

Answer 2 If You are sharing this handle without duplication and no referenc counting and so on, you only need to Close it one time and it will be invalid.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜