1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- #ifndef MODULE_I_THREAD_H
- #define MODULE_I_THREAD_H
- #include<atomic>
- #include<boost/thread.hpp>
- #include<mutex>
- #include<log.h>
- /**
- * @brief 线程接口类,重写run函数,改变睡眠时间 sleep_ms
- */
- class i_thread
- {
- public:
- i_thread()
- {
- sleep_ms=5*1000;
- }
- virtual ~i_thread(){}
- /**
- * @brief 启动线程
- */
- void start()
- {
- _thread_flag=true;
- _thread_handler=boost::thread(&i_thread::thread_proc, this);
- }
- /**
- * @brief 终止线程
- */
- void stop()
- {
- _thread_flag=false;
- _thread_handler.interrupt();
- }
- ///线程睡眠时间 毫秒
- std::atomic<int> sleep_ms;
- protected:
- /// 互斥量
- std::mutex _mutex;
- /**
- * @brief 线程函数
- */
- virtual void run(){}
- private:
- /// 线程句柄
- boost::thread _thread_handler;
- /// 线程标志
- std::atomic<bool> _thread_flag;
- void thread_proc()
- {
- while(_thread_flag)
- {
- try
- {
- run();
- boost::this_thread::sleep_for(boost::chrono::milliseconds(sleep_ms));
- }
- catch (const boost::thread_interrupted&)
- {
- }
- catch(const std::exception&e)
- {
- log_error("捕获到异常:%s",e.what());
- }
- catch(...)
- {
- log_error("捕获到未知异常");
- }
- }
- }
- };
- #endif // MODULE_I_THREAD_H
|