智能指针实现代码--定时器实例
话不多说,直接看实现源码。
typedef unsigned long ULONG;typedef unsigned __int64 UINT64;class CTimer{public:CTimer(){}~CTimer(){}public:void RegisterTimer( UINT64 id, ULONG period, UINT64 times );void UnRegisterTimer( UINT64 id );void RunTimer();private:struct _TimerInfo : public Counter<>{ULONG ulLastTime;ULONG ulNextTime;ULONG ulPeriod;UINT64 uiTimes;_TimerInfo():uiTimes(0),ulLastTime(0),ulNextTime(0),ulPeriod(0){}};typedef map< UINT64, SmartPointer<_TimerInfo> >_TimerMap;_TimerMap m_timer;static UINT64 m_id;};UINT64 CTimer::m_id = 0;void CTimer::RegisterTimer( UINT64 id, ULONG period, UINT64 times ){SmartPointer<_TimerInfo> timer(new _TimerInfo);timer->ulLastTime = ::GetTickCount();timer->ulNextTime = timer.m_p->ulLastTime + period;timer->ulPeriod = period;timer->uiTimes = times;//m_id += 1;m_timer.insert(make_pair(id, timer));}void CTimer::UnRegisterTimer(UINT64 id){_TimerMap::iterator iter = m_timer.find(id);if( iter != m_timer.end()){m_timer.erase(id);}}void CTimer::RunTimer(){while( 1 ){_TimerMap::iterator iter = m_timer.begin();for( ;iter != m_timer.end(); ++iter){ULONG now = ::GetTickCount();if( now >= iter->second->ulNextTime ){if( m_id == 3 ) break;printf("timer id is:%d\n",iter->first);iter->second->ulLastTime = now;iter->second->ulNextTime = now + iter->second->ulPeriod;m_id += 1;}}}}int _tmain(int argc, _TCHAR* argv[]){CTimer timer;//timer.RegisterTimer(1, 1000, 5);timer.RegisterTimer(2, 2000, 3);timer.RunTimer();return 0;}