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

来源:互联网 发布:推荐俄罗斯代购知乎 编辑:程序博客网 时间:2024/06/06 01:12

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


 #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 functionT _func; boost::mutex _mutex;};#endif


0 0