| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- #include "UnivThreadBase.h"
- UnivThreadBase::UnivThreadBase(std::string loggerName)
- {
- m_logger = spdlog::get(loggerName);
- if(m_logger == nullptr)
- {
- SPDLOG_ERROR("{} logger is nullptr", loggerName);
- return;
- }
- m_isRunning = false;
- m_threadState = eThreadState::Thread_STOPPED;
- }
- UnivThreadBase::~UnivThreadBase()
- {
- }
- /* 启动线程,非阻塞 */
- void UnivThreadBase::thread_task()
- {
- /* 初始化数据 */
- if(!initData())
- {
- SPDLOG_LOGGER_WARN(m_logger, "{} 线程初始化失败", m_logBase);
- return;
- }
- m_isRunning = true;
- m_threadState = eThreadState::Thread_RUNNING;
- SPDLOG_LOGGER_DEBUG(m_logger, "{} 线程启动", m_logBase);
- /* 线程任务,阻塞等待 */
- task();
- /* 清理数据 */
- clearData();
- m_threadState = eThreadState::Thread_STOPPED;
- m_condVar.notify_all();
- SPDLOG_LOGGER_INFO(m_logger, "{} 线程已停止", m_logBase);
- }
- /* 停止线程,阻塞等待线程退出 */
- void UnivThreadBase::thread_stop_block()
- {
- thread_stop();
- std::this_thread::sleep_for(std::chrono::milliseconds(100));
- std::unique_lock<std::mutex> lock(m_mutex);
- m_condVar.wait(lock, [this]() {
- return m_threadState == eThreadState::Thread_STOPPED;
- });
- }
- /* 停止线程,非阻塞 */
- void UnivThreadBase::thread_stop()
- {
- SPDLOG_LOGGER_INFO(m_logger, "开始停止 {} 线程", m_logBase);
- m_isRunning = false;
- m_condVar.notify_all();
- }
- /* 获取线程状态名称 */
- std::string UnivThreadBase::threadStateString(eThreadState state)
- {
- switch(state)
- {
- case eThreadState::Thread_None:
- return "无状态";
- case eThreadState::Thread_INIT:
- return "初始化";
- case eThreadState::Thread_RUNNING:
- return "运行中";
- case eThreadState::Thread_STOPPING:
- return "停止中";
- case eThreadState::Thread_STOPPED:
- return "已停止";
- case eThreadState::Thread_ERROR:
- return "线程错误";
- default:
- return "未知的线程状态类型";
- }
- }
- /* 线程延时, 输入ms */
- void UnivThreadBase::thread_sleep_ms(int sleepMs)
- {
- std::unique_lock<std::mutex> lock(m_mutex);
- m_condVar.wait_for(lock, std::chrono::milliseconds(sleepMs));
- }
- /* 线程延时, 单位秒 */
- void UnivThreadBase::thread_sleep_s(int sleepS)
- {
- std::unique_lock<std::mutex> lock(m_mutex);
- m_condVar.wait_for(lock, std::chrono::seconds(sleepS));
- }
|