#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 (boost::thread_interrupted&)
            {
            }
            catch(std::exception&)
            {
                //log_error("thread_proc exception 结束线程 i_thread");
            }
        }
    }
};

#endif // MODULE_I_THREAD_H