'Windows SetTimer() vs using SleepConditionVariableCS()
I currently have a timer implemented using tbb::condition_variable which under the covers uses native Windows call SleepConditionVariableCS() . One of my co-workers think that if I use Windows SetTimer() there would be a performance gain. My question is, is my co-worker's statement true?
Implementation details: Main function: calls a callback function after the time-out value. Additional functionality: the time-out value can be reset, should be able to stop the timer.
Following is the code I can use to implement the main functionality of the timer:
Using SetTimer():
void CALLBACK TimerProc(HWND, UINT, UINT, DWORD); // this is the callback function
// it will set the j=0 in the while loop below
UINT id;
MSG msg;
id = SetTimer(NULL, 0, 3000, (TIMERPROC) TimerProc);
// thread waits until j=0
while(j) {
GetMessage(&msg, NULL, 0, 0);
DispatchMessage(&msg);
}
KillTimer(NULL, id);
Using SleepConditionVariableCS():
CRITICAL_SECTION CritSection;
CONDITION_VARIABLE ConditionVar;
EnterCriticalSection(&CritSection);
SleepConditionVariableCS(&ConditionVar, &CritSection, INFINITE);
//Here call the callback function.
Solution 1:[1]
Your co-worker's statement is most likely (like, 99.99%) false.
Ask yourself is there a performance issue with the existing code? If yes, can your co-worker prove that the condition variable is the performance bottleneck? As in, did they run any benchmarks?
SleepConditionVariableCS
is used for thread synchronization, whileSetTimer
is used to queue (small amount of) work asynchronously. They literally have nothing in common.TimerProc
is called from default window procedure so that means you need a window and a message pump.If I am not mistaken,
TimerProc
is not meant for long background processing.Any callback function called by a periodic timer must be reentrant and thread-safe and guard any use of shared resources by using one of the many available thread synchronization primitives (such as mutexes, SRW locks, semaphores, critical sections, and condition variables).
TL;DR — unless thread synchronization is not necessary, you cannot replace condition variable with a timer callback.
Finally, depending on the amount of work done in the callback, either using the timer queue timers or waitable timers would be much better than using SetTimer
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Igor Levicki |