77 lines
2.3 KiB
C++

// Copyright (C) 2003 Intel Corporation
//////////////////////////////////////////////////////////////////////////
// TimerManager.h
//
// This file contains the definition of the TimerManager class.
// The TimerManager is responsible for providing an abstraction of
// multiple timers, while implemented with a central timer-managing thread.
//
// Usage:
// Register a timer function using the "registerCallback" method.
// if the "recurring" parameter is false, this will be a "single-shot"
// timer.
// Stop a recurring timer using the "unregisterCallback" method. single-shot
// timers should not be unregistered.
//
// Implementation overview:
// The TimerManager uses a separate thread to implement a timer routine.
// This thread is put in standby while no timer callback should be called,
// and wakes only on timer events, or when another thread (un)registers
// a timer. Note that the timer callbacks are called from within the timer
// thread context. An Event object is used to synchronize the thread with
// the the registration methods. A Semaphore object is used to lock
// the calback list.
//////////////////////////////////////////////////////////////////////////
#ifndef _LAD_TIMER_MANAGER_H
#define _LAD_TIMER_MANAGER_H
#include "Semaphore.h"
#include "Thread.h"
#include "Event.h"
#include "SPtr.h"
#include <vector>
using namespace std;
class CallbackParam{
public:
CallbackParam(){}
virtual ~CallbackParam(){}
};
class TimerManager : public Thread {
public:
typedef void (*CallbackFunction) (SPtr<CallbackParam>);
static TimerManager* instance();
static void stop();
int registerCallback(long interval, CallbackFunction func, SPtr<CallbackParam> param = SPtr<CallbackParam>(0), bool recurring = true);
void unregisterCallback(int timer_id);
private:
TimerManager();
virtual void run(); // from Thread
virtual ~TimerManager();
struct _Callback {
CallbackFunction function;
SPtr<CallbackParam> param;
int timerId;
long nextExpiration;
long interval;
bool recurring;
SPtr<Semaphore> runLock;
};
Event _registration;// to mark when a new timer has register / unregistered
Semaphore _sem; // to lock the queue
vector<_Callback> _callbacks;
int _timerId;
bool _exitThread;
static TimerManager* _instance;
};
#endif //_LAD_TIMER_MANAGER_H