Windows state variable and event

To synchronize threads in WinNT v6.x or later, we can use either the primitive of the new condition variable or the Windows event. Consider the following two approaches: we want workers to start at the same time when "go" is installed basically, otherwise they should all be blocked.

/*language C code*/ /*Windows Condition Variable*/ int go=0; CONDITION_VARIABLE cv; SRWLOCK lock; void workers() { AcquireSRWLockShared(&lock); if(go==0) { SleepConditionVariableSRW(&cv, &lock, INFINITE, CONDITION_VARIABLE_LOCKMODE_SHARED); } ReleaseSRWLockShared(&lock); /* Workers continue... */ } void main() { int i; InitializeConditionVariable(&cv); InitializeSRWLock(&lock); for(i=0;i<10;i++) { CreateThread(0, 0, workers, 0, 0, 0); } AcquireSRWLockExclusive(&lock); go=1; ReleaseSRWLockExclusive(&lock); WakeAllConditionVariable(&cv); } 

or

 /*language C code*/ /*Windows Event*/ HANDLE go; void workers() { WaitForSingleObject(go, INFINITE); /* Workers continue... */ } void main() { int i; go=CreateEvent(0,1,0,0); /*No security descriptor, Manual Reset, initially 0, no name*/ for(i=0;i<10;i++) { CreateThread(0, 0, workers, 0, 0, 0); } SetEvent(go); } 

In the first approach, workers lock on SleepConditionVariableSRW and wake up WakeAllConditionVariable . In the second, they lock on WaitForSingleObject and wake up SetEvent .

Which one is better in practice, only taking into account overhead? (hint: context switch, lock conflict, overhead of blocking threads)

I would choose the first, but did not lack a justification.

+6
c multithreading windows condition-variable readerwriterlockslim
source share
2 answers

This specific use case is ideal for an event: it is a one-time process in which all pending threads must be woken up.

Variable conditions are better suited for things like queues, where there is a related predicate that may or may not be true when a thread is waiting for a thread to wake up (for example, items in a queue --- they may have been consumed by another thread), or where it is important so that the thread invoked is one of those already waiting when the condition variable is notified, and not the one that comes after that.

In addition, as Hans pointed out, Windows state variables for Windows only work in Vista or later, so you cannot use them if the compatibility issue with Windows XP is a concern.

+5
source share

Support for state variables requires Vista or better. Usually, when the dollar stops, XP support is unfortunately still important. Your second snippet also has a significant advantage that is trivial to understand. I don’t know what you are trying to do in the first, it looks wrong.

+2
source share

All Articles