views:

558

answers:

2

What is the difference between event objects and condition variables? I am asking in context of WIN32 API.

+2  A: 

They are very similar, but event objects work across process boundaries, whereas condition variables do not. From the MSDN documentation on condition variables:

Condition variables are user-mode objects that cannot be shared across processes.

From the MSDN documentation on event objects:

Threads in other processes can open a handle to an existing event object by specifying its name in a call to the OpenEvent function.

Vinay Sajip
No, Remy Lebeau is closer to truth. Condition Variable is something that was recently imported from Unix into Windows. Event object is a pale imitation of Condition. In fact, it's nontrivial to implement Condition Var given only Event Object and Mutex. See http://www.cse.wustl.edu/~schmidt/win32-cv-1.html
Arkadiy
+8  A: 

Event objects are kernel-level objects. They can be shared across process boundaries, and are supported on all Windows OS versions. They can be used as their own standalone locks to shared resources, if desired. Since they are kernel objects, the OS has limitations on the number of available events that can be allocated at a time.

Condition Variables are user-level objects. They cannot be shared across process boundaries, and are only supported on Vista/2008 and later. They do not act as their own locks, but require a separate lock to be associated with them, such as a critical section. Since they are user- objects, the number of available variables is limited by available memory. When a Conditional Variable is put to sleep, it automatically releases the specified lock object so another thread can acquire it. When the Conditional Variable wakes up, it automatically re-acquires the specified lock object again.

In terms of funtionality, think of a Conditional Variable as a logic combination of multiple objects working together - an event object and a lock object. When the Condition Variable is put to sleep, it releases the lock, resets the event, waits for the event to be signaled, and then re-acquires the lock. So, if you were to use a critical section as the lock object, then SleepConditionalVariableCS() acts like a sequence of calls to ResetEvent(), LeaveCriticalSection(), WaitForSingleObject(), and EnterCriticalSection(). Technically, that is not what a Conditional Variable actually does internally, but your code does not need to care about those details.

Remy Lebeau - TeamB