Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

win32 Handles and multithread

In our application, there is a heavy use of win32 HANDLEs, using CreateEvent, SetEvent/ResetEvent, so as to perform synchronization mechanisms.

A colleague of mine has asked me if accessing the HANDLEs for events was thread-safe.

I could not answer, since HANDLEs are not thread safe for any GDI object...

But since events are aimed towards multithread synchronization, I could not imagine they arent thread safe.

Could you confirm this ?

like image 329
Stephane Rolland Avatar asked May 18 '26 10:05

Stephane Rolland


2 Answers

All handles you obtain from functions in Kernel32 are thread-safe, unless the MSDN Library article for the function explicitly mentions it is not. There's an easy way to tell from your code, such a handle is closed with CloseHandle().

What you do with the handle may not necessarily be thread safe, Windows won't help when you call SetEvent() twice but WaitForSingleObject() only once. Which might be a threading race in your program, depending on how you use the event.

like image 174
Hans Passant Avatar answered May 21 '26 00:05

Hans Passant


Depends on the type of handle.

A synchronization handle (like one created by CreateEvent) is by definition thread safe. A file handle, when written to by multiple threads simultaneously, not so much.

like image 44
Jonathan Potter Avatar answered May 20 '26 22:05

Jonathan Potter