BaseCalculateThread.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #include "BaseCalculateThread.h"
  2. BaseCalculateThread::BaseCalculateThread(CalculateThreadInfo_t& threadInfo)
  3. : m_threadInfo(threadInfo)
  4. {
  5. m_logger = spdlog::get("Calculate");
  6. if (m_logger == nullptr)
  7. {
  8. fmt::print("BaseCalculateThread: Calculate Logger not found.\n");
  9. return;
  10. }
  11. }
  12. /**
  13. * @brief 线程任务函数,创建线程时会调用此函数
  14. */
  15. void BaseCalculateThread::threadTask()
  16. {
  17. m_logBase = fmt::format("对比项: {} 线程类型: {}",
  18. m_threadInfo.compareItemInfo.strName.toStdString(),
  19. static_cast<int>(m_threadInfo.threadType));
  20. m_threadInfo.threadState = EThreadState::State_Running;
  21. m_isRunning = true;
  22. m_isStop = false;
  23. /* 执行任务,并阻塞到这个函数中,直到任务退出 */
  24. task();
  25. m_isRunning = false;
  26. /* 清理资源 */
  27. /* 设置全局的线程状态 */
  28. m_threadInfo.threadState = EThreadState::State_Stopped;
  29. m_isStop.store(true);
  30. SPDLOG_LOGGER_INFO(m_logger, "★ {} 执行结束", m_logBase);
  31. }
  32. /* 更新线程信息 */
  33. void BaseCalculateThread::updateThreadInfo(const CalculateThreadInfo_t& threadInfo)
  34. {
  35. if(threadInfo.compareItemInfo.nID != m_threadInfo.compareItemInfo.nID)
  36. {
  37. SPDLOG_LOGGER_WARN(m_logger, "新传入的对比项ID {} 和当前线程的对比项ID {} 不匹配,无法更新线程信息",
  38. threadInfo.compareItemInfo.nID, m_threadInfo.compareItemInfo.nID);
  39. }
  40. m_threadInfoNew = threadInfo;
  41. m_isUpdate = true;
  42. }
  43. /* 停止线程,只设置个停止标志,不阻塞等待 */
  44. void BaseCalculateThread::stopThread()
  45. {
  46. m_isRunning = false;
  47. SPDLOG_LOGGER_INFO(m_logger, "{} 线程设置为停止状态", m_logBase);
  48. }
  49. /* 停止线程 */
  50. void BaseCalculateThread::stopThreadBlock()
  51. {
  52. m_isRunning = false;
  53. while(m_isStop.load() == false)
  54. {
  55. /* 100us检查一次 */
  56. std::this_thread::sleep_for(std::chrono::microseconds(100));
  57. }
  58. }
  59. /* 更新线程信息 */
  60. bool BaseCalculateThread::updateThreadInfoInternal()
  61. {
  62. if(!m_isUpdate)
  63. {
  64. return false;
  65. }
  66. /* 只更新对比项的信息 */
  67. m_threadInfo.compareItemInfo = m_threadInfoNew.compareItemInfo;
  68. m_isUpdate = false;
  69. // SPDLOG_LOGGER_INFO(m_logger, "{} 更新线程信息", m_logBase);
  70. return true;
  71. }