Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // usp_threadpooltimer.h
- #pragma once
- #include "usp_config.h"
- #include "usp_windowsh.h"
- #include "usp_callwrap.h"
- #include "usp_rwspinlock.h"
- class ThreadpoolTimerVista
- {
- };
- class ThreadPoolTimerXP
- {
- HANDLE timerQueueTimer;
- typedef std::function<void(BOOL)> TargetFunction;
- TargetFunction target;
- RWSpinLock lock;
- public:
- ThreadPoolTimerXP()
- : timerQueueTimer(0)
- {
- }
- ~ThreadPoolTimerXP()
- {
- StopTimer();
- }
- template<typename T>
- void SetCallback(T *targetObject, void (T::*member)(BOOLEAN))
- {
- target = TargetFunction(
- [=](BOOLEAN fired)
- {
- (targetObject->*member)(fired);
- });
- }
- static void NTAPI TimerCallback(void *parameter, BOOLEAN timerOrWaitFired)
- {
- auto self = reinterpret_cast<ThreadPoolTimerXP*>(parameter);
- // Attempt to acquire a shared lock
- auto hold(self->lock.TryHoldShared());
- // If it was acquired, invoke the callback, else drop the callback
- // because we must be destructing this object
- if (hold.IsHeld())
- self->target(timerOrWaitFired);
- }
- BOOL SetTimer(DWORD dueTime, DWORD period)
- {
- if (timerQueueTimer)
- {
- // Change existing timer
- auto ok = ChangeTimerQueueTimer(NULL, timerQueueTimer,
- dueTime, period);
- return ok;
- }
- else
- {
- // Create timer
- auto ok = CreateTimerQueueTimer(&timerQueueTimer, NULL,
- TimerCallback, this,
- dueTime, period, WT_EXECUTEDEFAULT);
- return ok;
- }
- }
- void StopTimer()
- {
- auto curTimer = Interlocked::Xchg(&timerQueueTimer, (HANDLE)0);
- if (curTimer)
- DeleteTimerQueueTimer(NULL, curTimer, INVALID_HANDLE_VALUE);
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement