c++ 时间轮定时器实现-深蓝源码网


时间: 2020-09-03 00:08:26 人气: 2279 评论: 0

前言

之所以写这篇文章,是在一篇博客中看到了时间轮定时器这个东西,感觉很是惊艳,https://www.cnblogs.com/zhongwencool/p/timing_wheel.html。在以前写windows 程序的时候,windows API 自己就实现了SetTimer 这个调用,在超时后会触发OnTimer的回调,然后通过timer_id 调用我们自己事件处理函数,但是在后台开发中,一般都需要自己实现,这里根据博客实现了自己的定时器。

实现

头文件定义TimeWheel.h

/************************************************************************/
/* TimeWheel实现了一个毫秒级别的定时器,最大支持到分钟级别                                                                     */
/************************************************************************/

#pragma once
#include<functional>
#include<list>
#include<thread>
#include<mutex>

typedef struct TimePos_
{
	int ms_pos;
	int s_pos;
	int min_pos;
}TimePos;

typedef struct EventInfo_
{
	int interval;
	std::function<void(void)> call_back;
	TimePos time_pos;
	int timer_id;

}EventInfo;

class TimeWheel
{
public:
	TimeWheel();
	~TimeWheel();
public:
	/*step 以毫秒为单位,表示定时器最小时间粒度
	 *max_timer 表示定时器所能接受的分钟时间间隔
	 */
	int InitTimerWheel(int step,int max_min);
	int AddTimer(int interval, std::function<void(void)>& call_back);
	int DeleteTimer(int timer_id);

private:
	int DoLoop();
	int GenerateTimerID();
	int InsertTimer(int diff_ms,EventInfo& einfo);
	int GetNextTrigerPos(int interval,TimePos& time_pos);
	int GetMS(TimePos time_pos);
	int DealTimeWheeling(std::list<EventInfo> leinfo);
private:
	std::list<EventInfo> *_pCallbackList = nullptr;
	std::mutex _mutex;

	TimePos _time_pos;

	int _lowCount = 0;
	int _midCount = 0;
	int _highCount = 0;

	int _step_ms = 0;

	int _timer_count = 0;

};

源文件实现TimerWheel.cpp

#include "TimeWheel.h"
#include <iostream>
#include <windows.h>
using namespace std;

TimeWheel::TimeWheel()
{
	memset(&_time_pos, 0, sizeof(_time_pos));
	
}


TimeWheel::~TimeWheel()
{
}
int TimeWheel::InitTimerWheel(int step_ms, int max_min)
{
	if (1000 % step_ms != 0)
	{
		cout << "step is not property, should be devided by 1000" << endl;
		return -1;
	}
	int msNeedCount = 1000 / step_ms;
	int sNeedCount = 60;
	int minNeedCount = max_min;

	_pCallbackList = new std::list<EventInfo>[msNeedCount + sNeedCount + minNeedCount];
	_step_ms = step_ms;

	_lowCount = msNeedCount;
	_midCount = sNeedCount;
	_highCount = minNeedCount;

	std::thread th([&]{
		this->DoLoop();
	});

	th.detach();
	return 0;
}
int TimeWheel::AddTimer(int interval, std::function<void(void)>& call_back)
{
	if (interval < _step_ms || interval % _step_ms != 0 || interval >= _step_ms * _lowCount * _midCount * _highCount)
	{
		cout << "time interval is invalid" << endl;
		return -1;
	}

	std::unique_lock<std::mutex> lock(_mutex);

	EventInfo einfo = {0};
	einfo.interval = interval;
	einfo.call_back = call_back;
	einfo.time_pos.ms_pos = _time_pos.ms_pos;
	einfo.time_pos.s_pos = _time_pos.s_pos;
	einfo.time_pos.min_pos = _time_pos.min_pos;
	einfo.timer_id = GenerateTimerID();
	 
	InsertTimer(einfo.interval,einfo);

	_timer_count++;

	cout << "insert timer success time_id: " << einfo.timer_id << endl;
	return einfo.timer_id;
}
int TimeWheel::DeleteTimer(int time_id)
{
	std::unique_lock<std::mutex> lock(_mutex);
	int i = 0;
	int nCount = _lowCount + _midCount + _highCount;
	for (i = 0; i < nCount; i++)
	{
		std::list<EventInfo>& leinfo = _pCallbackList[i];
		for (auto item = leinfo.begin(); item != leinfo.end();item++)
		{
			if (item->timer_id == time_id)
			{
				item = leinfo.erase(item);
				return 0;
			}
		}
	}

	if (i == nCount)
	{
		cout << "timer not found" << endl;
		return -1;
	}

	return 0;
}
int TimeWheel::DoLoop()
{
	cout << "........starting loop........" << endl;
	static int nCount = 0;
	while (true)
	{
		this_thread::sleep_for(chrono::milliseconds(_step_ms));
		std::unique_lock<std::mutex> lock(_mutex);
		cout << ".........this is " << ++nCount <<"  loop........."<< endl;
		TimePos pos = {0};
		TimePos last_pos = _time_pos;
		GetNextTrigerPos(_step_ms, pos);
		_time_pos = pos;

		if (pos.min_pos != last_pos.min_pos)
		{
			list<EventInfo>& leinfo = _pCallbackList[_time_pos.min_pos + _midCount + _lowCount];
			DealTimeWheeling(leinfo);
			leinfo.clear();
		}
		else if (pos.s_pos != last_pos.s_pos)
		{
			list<EventInfo>& leinfo = _pCallbackList[_time_pos.s_pos + _lowCount];
			DealTimeWheeling(leinfo);
			leinfo.clear();
		}
		else if (pos.ms_pos != last_pos.ms_pos)
		{
			list<EventInfo>& leinfo = _pCallbackList[_time_pos.ms_pos];
			DealTimeWheeling(leinfo);
			leinfo.clear();
		}
		else
		{
			cout << "error time not change" << endl;
			return -1;
		}
		lock.unlock();
	}
	return 0;
}
int TimeWheel::GenerateTimerID()
{
	int x = rand() % 0xffffffff;
	int cur_time = time(nullptr);
	return x | cur_time | _timer_count;
}

int TimeWheel::InsertTimer(int diff_ms,EventInfo &einfo)
{
	TimePos time_pos = {0};

	GetNextTrigerPos(diff_ms, time_pos);

	if (time_pos.min_pos != _time_pos.min_pos)
		_pCallbackList[_lowCount + _midCount + time_pos.min_pos].push_back(einfo);
	else if (time_pos.s_pos != _time_pos.s_pos)
		_pCallbackList[_lowCount + time_pos.s_pos].push_back(einfo);
	else if (time_pos.ms_pos != _time_pos.ms_pos)
		_pCallbackList[time_pos.ms_pos].push_back(einfo);

	return 0;
}

int TimeWheel::GetNextTrigerPos(int interval, TimePos& time_pos)
{
	int cur_ms = GetMS(_time_pos)
						 技术沙龙 教程文章 热点综合					

评论