Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling CloseHandle after calling SetEvent

I have a thread running in my application. Inside the thread I am waiting on an auto reset event to exit. I want to make sure that i close the handle of the event after i use it. Ihave two options.

  1. Calling CloseHandle of the event immediately after calling SetEvent
  2. Calling CloseHandle after the line WaitForSingleObject

Please suggest me which one is the right approach.

like image 986
Jeeva Avatar asked Jun 23 '11 10:06

Jeeva


3 Answers

Close the handle when all threads have finished using it. After the WaitForSingleObject sounds sensible to me (because if it succeeds, the SetEvent must have completed).

Alternatively - give each thread its own copy of the handle (eg via DuplicateHandle) and have each close their copy when they're finished. That's much harder to get wrong and requires less analysis of the code.

like image 108
Alan Stokes Avatar answered Sep 24 '22 21:09

Alan Stokes


Calling CloseHandle after SetEvent doesn't make sense to me. You should (if required) call CloseHandle after WaitForSingleObject only.

like image 41
Ajay Avatar answered Sep 25 '22 21:09

Ajay


Close event handle when you are sure that event has done its job and is not needed any more. In you case that is after you detect it has been set. So, close event handle after WaitForSingleObject unblocks.

like image 37
Bojan Komazec Avatar answered Sep 22 '22 21:09

Bojan Komazec