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.
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); } 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
HANDLE go; void workers() { WaitForSingleObject(go, INFINITE); } void main() { int i; go=CreateEvent(0,1,0,0); 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.
c multithreading windows condition-variable readerwriterlockslim
Yz
source share