1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- #ifndef MODULE_I_THREAD_H
- #define MODULE_I_THREAD_H
- #include<atomic>
- #include<boost/thread.hpp>
- #include<mutex>
- #include<log.h>
- class i_thread
- {
- public:
- i_thread()
- {
- sleep_ms=5*1000;
- }
- virtual ~i_thread(){}
-
- void start()
- {
- _thread_flag=true;
- _thread_handler=boost::thread(&i_thread::thread_proc, this);
- }
-
- void stop()
- {
- _thread_flag=false;
- _thread_handler.interrupt();
- }
-
- std::atomic<int> sleep_ms;
- protected:
-
- std::mutex _mutex;
-
- 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
|