1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- #ifndef THREADGUARDIAN_H
- #define THREADGUARDIAN_H
- #include <thread>
- #include <mutex>
- #include <atomic>
- #include <unordered_map>
- #include <functional>
- #include <string>
- #include <chrono>
- // 前向声明
- class MppManager;
- class RKNNManager;
- // 线程状态结构体
- struct ThreadInfo {
- int threadIndex; // 线程索引
- std::string name; // 线程名称
- std::thread::id threadId; // 线程ID
- bool isRunning; // 线程是否正在运行
- std::chrono::steady_clock::time_point lastAliveTime; // 上次活跃时间
- std::function<void(int)> restartFunc; // 重启函数
- };
- class ThreadGuardian {
- public:
- // 单例模式获取实例
- static ThreadGuardian &getInstance() {
- static ThreadGuardian instance;
- return instance;
- }
- // 禁止拷贝和赋值
- ThreadGuardian(const ThreadGuardian &) = delete;
- ThreadGuardian &operator=(const ThreadGuardian &) = delete;
- // 启动监控
- void startMonitoring();
-
- // 停止监控
- void stopMonitoring();
-
- // 注册MppDecoder线程
- void registerMppThread(int threadIndex, std::function<void(int)> restartFunc);
-
- // 注册AIManager线程
- void registerAIThread(int threadIndex, std::function<void(int)> restartFunc);
-
- // 线程心跳更新
- void updateThreadHeartbeat(std::string threadName);
-
- // 移除线程监控
- void unregisterThread(std::string threadName);
- private:
- // 私有构造函数
- ThreadGuardian();
- ~ThreadGuardian();
-
- // 监控线程函数
- void monitorThreads();
-
- // 恢复线程
- void restartThread(const ThreadInfo& threadInfo);
- private:
- std::thread m_monitorThread; // 监控线程
- std::atomic<bool> m_running; // 监控线程运行标志
- std::mutex m_threadMapMutex; // 线程映射锁
- std::unordered_map<std::string, ThreadInfo> m_threads; // 线程信息映射
-
- const std::chrono::seconds m_checkInterval{5}; // 检查间隔时间
- const std::chrono::seconds m_threadTimeout{15}; // 线程超时时间
- };
- #endif // THREADGUARDIAN_H
|