#ifndef AV_BASE_MEDIA_THREAD_BASE_H #define AV_BASE_MEDIA_THREAD_BASE_H #include "types.h" #include #include #include #include #include #include #include namespace av { // 线程状态枚举 enum class ThreadState { STOPPED, STARTING, RUNNING, STOPPING }; // 线程基类 class ThreadBase { public: ThreadBase(); virtual ~ThreadBase(); // 禁止拷贝和移动 ThreadBase(const ThreadBase&) = delete; ThreadBase& operator=(const ThreadBase&) = delete; ThreadBase(ThreadBase&&) = delete; ThreadBase& operator=(ThreadBase&&) = delete; // 线程控制 bool start(); void stop(); void join(); // 状态查询 bool isRunning() const; bool isStopping() const; ThreadState getState() const; // 线程ID std::thread::id getThreadId() const; // 设置线程名称(用于调试) void setThreadName(const std::string& name); std::string getThreadName() const; // 回调设置 void setOnStarted(std::function callback); void setOnFinished(std::function callback); void setOnError(std::function callback); // 等待条件 void waitForCondition(std::function condition, int timeoutMs = -1); void notifyCondition(); protected: // 子类需要实现的运行逻辑 virtual void run() = 0; // 辅助方法 bool shouldExit() const; void sleepMs(int ms); bool waitForMs(int ms); // 可中断的等待 // 错误处理 void reportError(const std::string& error); // 线程同步 std::mutex m_mutex; std::condition_variable m_condition; private: void threadEntry(); void setState(ThreadState state); void cleanup(); // 线程控制 std::atomic m_exitRequested{false}; std::atomic m_state{ThreadState::STOPPED}; std::unique_ptr m_thread; // 线程信息 std::string m_threadName; std::thread::id m_threadId; // 回调函数 std::function m_onStarted; std::function m_onFinished; std::function m_onError; // 同步控制 mutable std::mutex m_stateMutex; std::condition_variable m_stateCondition; // 超时控制 static constexpr int DEFAULT_JOIN_TIMEOUT_MS = 5000; }; // 工作线程模板类(用于简单的循环工作) template class WorkerThread : public ThreadBase { public: explicit WorkerThread(WorkFunc workFunc, int intervalMs = 10) : m_workFunc(std::move(workFunc)) , m_intervalMs(intervalMs) { } void setInterval(int intervalMs) { std::lock_guard lock(m_mutex); m_intervalMs = intervalMs; } int getInterval() const { std::lock_guard lock(m_mutex); return m_intervalMs; } protected: void run() override { while (!shouldExit()) { try { m_workFunc(); } catch (const std::exception& e) { reportError("Work function exception: " + std::string(e.what())); } catch (...) { reportError("Unknown work function exception"); } if (!shouldExit()) { waitForMs(m_intervalMs); } } } private: WorkFunc m_workFunc; int m_intervalMs; }; // 便捷的工作线程创建函数 template std::unique_ptr> makeWorkerThread(WorkFunc workFunc, int intervalMs = 10) { return std::make_unique>(std::move(workFunc), intervalMs); } } // namespace av #endif // AV_BASE_THREAD_BASE_H