UnivThreadBase.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #include "UnivThreadBase.h"
  2. UnivThreadBase::UnivThreadBase(std::string loggerName)
  3. {
  4. m_logger = spdlog::get(loggerName);
  5. if(m_logger == nullptr)
  6. {
  7. SPDLOG_ERROR("{} logger is nullptr", loggerName);
  8. return;
  9. }
  10. m_isRunning = false;
  11. m_threadState = eThreadState::Thread_STOPPED;
  12. }
  13. UnivThreadBase::~UnivThreadBase()
  14. {
  15. }
  16. /* 启动线程,非阻塞 */
  17. void UnivThreadBase::thread_task()
  18. {
  19. /* 初始化数据 */
  20. if(!initData())
  21. {
  22. SPDLOG_LOGGER_WARN(m_logger, "{} 线程初始化失败", m_logBase);
  23. return;
  24. }
  25. m_isRunning = true;
  26. m_threadState = eThreadState::Thread_RUNNING;
  27. SPDLOG_LOGGER_DEBUG(m_logger, "{} 线程启动", m_logBase);
  28. /* 线程任务,阻塞等待 */
  29. task();
  30. /* 清理数据 */
  31. clearData();
  32. m_threadState = eThreadState::Thread_STOPPED;
  33. m_condVar.notify_all();
  34. SPDLOG_LOGGER_INFO(m_logger, "{} 线程已停止", m_logBase);
  35. }
  36. /* 停止线程,阻塞等待线程退出 */
  37. void UnivThreadBase::thread_stop_block()
  38. {
  39. thread_stop();
  40. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  41. std::unique_lock<std::mutex> lock(m_mutex);
  42. m_condVar.wait(lock, [this]() {
  43. return m_threadState == eThreadState::Thread_STOPPED;
  44. });
  45. }
  46. /* 停止线程,非阻塞 */
  47. void UnivThreadBase::thread_stop()
  48. {
  49. SPDLOG_LOGGER_INFO(m_logger, "开始停止 {} 线程", m_logBase);
  50. m_isRunning = false;
  51. m_condVar.notify_all();
  52. }
  53. /* 获取线程状态名称 */
  54. std::string UnivThreadBase::threadStateString(eThreadState state)
  55. {
  56. switch(state)
  57. {
  58. case eThreadState::Thread_None:
  59. return "无状态";
  60. case eThreadState::Thread_INIT:
  61. return "初始化";
  62. case eThreadState::Thread_RUNNING:
  63. return "运行中";
  64. case eThreadState::Thread_STOPPING:
  65. return "停止中";
  66. case eThreadState::Thread_STOPPED:
  67. return "已停止";
  68. case eThreadState::Thread_ERROR:
  69. return "线程错误";
  70. default:
  71. return "未知的线程状态类型";
  72. }
  73. }
  74. /* 线程延时, 输入ms */
  75. void UnivThreadBase::thread_sleep_ms(int sleepMs)
  76. {
  77. std::unique_lock<std::mutex> lock(m_mutex);
  78. m_condVar.wait_for(lock, std::chrono::milliseconds(sleepMs));
  79. }
  80. /* 线程延时, 单位秒 */
  81. void UnivThreadBase::thread_sleep_s(int sleepS)
  82. {
  83. std::unique_lock<std::mutex> lock(m_mutex);
  84. m_condVar.wait_for(lock, std::chrono::seconds(sleepS));
  85. }