| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- #ifndef __UNIVTHREADBASE_H__
- #define __UNIVTHREADBASE_H__
- #include <atomic>
- #include <mutex>
- #include "spdlog/spdlog.h"
- enum class eThreadState
- {
- Thread_None = 0,
- Thread_INIT,
- Thread_RUNNING, /* 线程运行中 */
- Thread_STOPPING, /* 线程正在停止 */
- Thread_STOPPED, /* 线程已停止 */
- Thread_ERROR /* 线程错误 */
- };
- /* 通用线程基类 */
- class UnivThreadBase
- {
- public:
- UnivThreadBase(std::string loggerName);
- virtual ~UnivThreadBase();
- /* 启动线程 */
- virtual void thread_task();
- /* 停止线程,阻塞等待线程退出 */
- virtual void thread_stop_block();
- /* 停止线程,非阻塞 */
- virtual void thread_stop();
-
- /* 获取线程状态名称 */
- static std::string threadStateString(eThreadState state);
- protected:
- /* 线程任务 */
- virtual void task() = 0;
- /* 初始化数据 */
- virtual bool initData() = 0;
- /* 清理数据 */
- virtual void clearData() = 0;
- /* 线程延时, 单位毫秒 */
- void thread_sleep_ms(int sleepMs);
- /* 线程延时, 单位秒 */
- void thread_sleep_s(int sleepS);
- protected:
- std::shared_ptr<spdlog::logger> m_logger = nullptr;
- std::atomic_bool m_isRunning; /* 线程是否运行标志 */
- std::mutex m_mutex; /* 线程延时等待互斥锁 */
- std::condition_variable m_condVar; /* 线程延时等待条件变量 */
- std::atomic<eThreadState> m_threadState; /* 线程状态 */
- std::string m_logBase;
- };
- #endif // __UNIVTHREADBASE_H__
|