ThreadGuardian.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #ifndef THREADGUARDIAN_H
  2. #define THREADGUARDIAN_H
  3. #include <thread>
  4. #include <mutex>
  5. #include <atomic>
  6. #include <unordered_map>
  7. #include <functional>
  8. #include <string>
  9. #include <chrono>
  10. // 前向声明
  11. class MppManager;
  12. class RKNNManager;
  13. // 线程状态结构体
  14. struct ThreadInfo {
  15. int threadIndex; // 线程索引
  16. std::string name; // 线程名称
  17. std::thread::id threadId; // 线程ID
  18. bool isRunning; // 线程是否正在运行
  19. std::chrono::steady_clock::time_point lastAliveTime; // 上次活跃时间
  20. std::function<void(int)> restartFunc; // 重启函数
  21. };
  22. class ThreadGuardian {
  23. public:
  24. // 单例模式获取实例
  25. static ThreadGuardian &getInstance() {
  26. static ThreadGuardian instance;
  27. return instance;
  28. }
  29. // 禁止拷贝和赋值
  30. ThreadGuardian(const ThreadGuardian &) = delete;
  31. ThreadGuardian &operator=(const ThreadGuardian &) = delete;
  32. // 启动监控
  33. void startMonitoring();
  34. // 停止监控
  35. void stopMonitoring();
  36. // 注册MppDecoder线程
  37. void registerMppThread(int threadIndex, std::function<void(int)> restartFunc);
  38. // 注册AIManager线程
  39. void registerAIThread(int threadIndex, std::function<void(int)> restartFunc);
  40. // 线程心跳更新
  41. void updateThreadHeartbeat(std::string threadName);
  42. // 移除线程监控
  43. void unregisterThread(std::string threadName);
  44. private:
  45. // 私有构造函数
  46. ThreadGuardian();
  47. ~ThreadGuardian();
  48. // 监控线程函数
  49. void monitorThreads();
  50. // 恢复线程
  51. void restartThread(const ThreadInfo& threadInfo);
  52. private:
  53. std::thread m_monitorThread; // 监控线程
  54. std::atomic<bool> m_running; // 监控线程运行标志
  55. std::mutex m_threadMapMutex; // 线程映射锁
  56. std::unordered_map<std::string, ThreadInfo> m_threads; // 线程信息映射
  57. const std::chrono::seconds m_checkInterval{5}; // 检查间隔时间
  58. const std::chrono::seconds m_threadTimeout{15}; // 线程超时时间
  59. };
  60. #endif // THREADGUARDIAN_H