使用boost::function 实现一个 单例线程

所谓单例线程: 是指,线程只运行一个实例,


 

#ifndef __RM_RUN_ONCE__H__
#define __RM_RUN_ONCE__H__

#include "boost/scoped_ptr.hpp"
#include "boost/thread.hpp"

template <class T>  /* //NOTE: here only accept boost::function<> type*/
class RunOnce 
{
public:
	RunOnce(T f):_func(f)
	{
		//_thread.reset(new boost::thread(_func));
	};

	RunOnce(){};

	/*
	** set func obj
	*/
	void set_func(T f)
	{
		_func = f;
	}

	/*
	** try to run function, 
	** if the function is already running or completed, just skip over;
	*/
	int start()
	{

		boost::lock_guard<boost::mutex> lock(_mutex);

		if(!_thread || 
			! _thread->joinable())
		{
			_thread.reset(new boost::thread(_func));
		}
		return 0;
	};

	/*
	** first kill running case(if has),
	** then start a new one;
	*/
	int restart()
	{
		boost::lock_guard<boost::mutex> lock(_mutex);

		if(_thread)
		{
			_thread->interrupt();
			_thread->join();
			_thread->detach();
		}
		_thread.reset(new boost::thread(_func));

		return 0;
	};

	/*
	** wait thread finished
	*/
	void join()
	{
		boost::lock_guard<boost::mutex> lock(_mutex);
		if(!_thread)  _thread->join();
	};

	~RunOnce()
	{
		try{
			_thread->interrupt();
			//_thread->join();
			_thread->detach();
		}
		catch(...){}		
	};

private:
	boost::scoped_ptr<boost::thread> _thread;  //backward thread to run function
	T _func; 
	boost::mutex _mutex;
};

#endif


猜你喜欢

转载自blog.csdn.net/zztan/article/details/70256249