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?


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 hEventAbortProgram = 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.

Need Your Help

How can I fetch data from an HTTPS Url via Proxy?

java sockets ssl proxy

I am getting Connection timed out: connect.

rails 3.1.1 autocomplete

jquery ruby-on-rails-3 jquery-ui autocomplete

I'm trying to get autocomplete working under Rails 3.1.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.