Adi Levin's Blog for programmers

June 13, 2009

Thread synchronization using Events

An important mechanism for synchronizing threads is an Event. An event is an object of the operating system, that has two states: either signaled (set) or unsignaled (reset). An Event can be named, like a Mutex or a Semaphre, therefore, it can be used for inter-process synchronization.

Most commonly, events are used to signal that some operation has been completed. This enabled one process (or thread) to wait until another process (or thread) completes its task.

An event is created by calling CreateEvent, which returns a HANDLE to the event object. An existing named event can be access using OpenEvent.

HANDLE WINAPI CreateEvent(
  __in_opt  LPSECURITY_ATTRIBUTES lpEventAttributes, // Can be NULL, for default security attributes
  __in      BOOL bManualReset,  // TRUE=manual, FALSE=automatic
  __in      BOOL bInitialState, // TRUE=signaled, FALSE=unsignaled
  __in_opt  LPCTSTR lpName // Should be NULL for unnamed events (inter-thread synchronization)
);

Two types of events – manual and automatic

When CreateEvent is called, its second parameters determine the type of the event – either manual or automatic. An automatic event gets reset immediately when a wait function is returned (due to the event becoming signaled). Therefore, it is used to signal a single thread that an operation was completed. If several threads are simultaneously waiting for an auomatic event to become signaled, only one of them will pass the wait function.

A manual event does not get reset automatically by the wait function. it has to be manually reset. Therefore, it can be used to notify several threads in parallel about the completion of a task.

Setting an event and Waiting for an event

An event can be signaled and unsignaled by the methods SetEvent and ResetEvent.

BOOL WINAPI SetEvent(__in  HANDLE hEvent);
BOOL WINAPI ResetEvent(__in  HANDLE hEvent);

A thread waiting for the event uses WaitForSingleObject or WaitForMultipleObjects.

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: