使用boost线程定时器作为后台线程来切换主循环程序状态方法2

上一篇的方法主要使用的是:通过线程延时实

现的定时,并且只能定时一次,如果需要对此定时处理,就需要使用下面的定时器;

#include "stdafx.h"
#include <iostream>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
using namespace boost::asio;
using namespace boost;
using namespace std;



//循环状态
enum program_state
{
	state1,
	state2,
	state3,
	state4
};


/*
 定时器类的作用:将外部类的超时函数传递进来后,在定时器超时函数中进行调用;
 这样类之间的关系,清晰明了
*/
class ctimer
{
private:
	int		_timeout_len;
	bool	_is_remove_when_timeout;//
	boost::function<void()> f;		//委托函数类型为无参数无返回值
	thread* ptrThread;
public:
	//外部函数
	//
	~ctimer()
	{
		if (ptrThread != NULL)
		{	
			delete this->ptrThread;
			this->ptrThread = NULL;
		}
	}
	template<typename F>
	void InstallTimer(F f, int _timeout_len, bool _is_remove_when_timeout)
	{
		this->_timeout_len = _timeout_len;
		this->_is_remove_when_timeout = _is_remove_when_timeout;
		this->f = f;
		//开启线程
		ptrThread=new thread(bind(&ctimer::setTimer, this));
	}
	void RemoveTimer()
	{	
		this->_is_remove_when_timeout = true;
		this->_timeout_len = 1;
		this->f = NULL;
	}
	//定时器线程工作者函数
	void setTimer()
	{	

		io_service m_ios;

		//设置定时器,并设置回调函数
		deadline_timer t( m_ios, boost::posix_time::millisec(this->_timeout_len));
		t.async_wait(bind(&ctimer::timeout,this));//回调
	
		//阻塞在这里,等待事件
		m_ios.run();
	
		cout << "thread quit"<<endl;
	}
	//回调函数
	void timeout()
	{	
		//回调函数中调用外部的处理程序
		if (this->f!=NULL)
			this->f();
		if (this->_is_remove_when_timeout == false)
		{
			thread(bind(&ctimer::setTimer, this));
		}
	}
};


//测试类,工作者主类
class TestClassA
{
public:
	//定时器类对象
	ctimer* ptrTimer;
	TestClassA()
	{
		state = state1;
		ptrTimer = new ctimer;
	}
	~TestClassA()
	{
		delete ptrTimer;
	}
	
	//主程序当前状态
	program_state state;

	//当前状态定时器超时处理函数
	void  TimeoutCallbackPrint()
	{
		printf(" TimeoutCallbackPrint
");
	
		ptrTimer->RemoveTimer();//直接关闭定时器
		this->state = state2;
	}
	void run()
	{
		while (1)
		{	
			//状态循环扫描
			switch (this->state)
			{
			case state1:
				proc_state1();
				break;
			case state2: break;
			}

		}
	}
	//主程序当前状态,处理函数
	void proc_state1()
	{	
		//加入定时器,并将定时器回调函数的需要处理函数传入进去,并将参数传入
		ptrTimer->InstallTimer(bind(&TestClassA::TimeoutCallbackPrint,this),500, false);

		//死循环,进行收发处理
		while (this->state == state1)
		{
		}
	}
};

int _tmain(int argc, _TCHAR* argv[])
{	

	TestClassA *tc = new TestClassA();
	tc->run();//主程序在类中循环
	getchar();
	return 0;
}
原文地址:https://www.cnblogs.com/cdma/p/4494104.html