#ifndef MODULE_CONST_H #define MODULE_CONST_H /** * @brief 包含常用的常量,接口基类,工具类 * @author 戴月腾 * @date 2018-08-24 */ #include #include #include #include #include"db_api/CDBConnPool.h" #include"log.h" #include #include #include #include #include #include "websocket/constdef.h" #include"card.h" #include"area.h" #include"ya_event.h" #include"config_file.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 sleep_ms; protected: /// 互斥量 std::mutex _mutex; /** * @brief 线程函数 */ virtual void run(){} private: /// 线程句柄 boost::thread _thread_handler; /// 线程标志 std::atomic _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"); } } } }; template class singleton_base { public: static T *instance() { if(nullptr != _instance) { return _instance; } std::lock_guard ll(_mutex_singleton_base); if(nullptr == _instance) { _instance = new(std::nothrow) T(); } return _instance; } protected: //使继承者无法public构造函数和析构函数 singleton_base(){} //virtual ~singleton_base(){} private: //禁止拷贝构造和赋值运算符 singleton_base(const singleton_base&){} singleton_base &operator=(const singleton_base&){} //它的唯一工作就是在析构函数中析构Singleton的实例,所以private class Garbo { public: ~Garbo() { if (singleton_base::_instance) { delete singleton_base::_instance; singleton_base::_instance = nullptr; } } }; //定义一个静态成员变量,程序结束时,系统会自动调用它的析构函数,我们不需要访问这个变量,所以不需要初始化 static Garbo garbo; static T *_instance; static std::mutex _mutex_singleton_base; }; template T *singleton_base::_instance = nullptr; template std::mutex singleton_base::_mutex_singleton_base; #endif // MODULE_CONST_H