#ifndef VRTHREADPOOL_H #define VRTHREADPOOL_H #include #include #include #include #include #include "IVrThreadPool.h" #include "VrThread.h" class VrThreadPool : public IVrThreadPool { public: // maxThreadCount: 最大线程数,0 表示使用硬件并发数,-1 表示不限制 explicit VrThreadPool(int maxThreadCount = 0); ~VrThreadPool(); // 提交任务(线程池满时自动放入等待队列,有空闲线程时执行) // 返回值: VrThreadPoolError::Ok(0) 成功, 负值为错误码 virtual int ExecTask(ThreadExecFunc fExecFunc, void* pParam) override; // 停止线程池(停止所有工作线程并等待完成) void Stop(); // 等待所有已提交任务执行完成 // timeoutMs: 超时时间(毫秒),0 表示无限等待 // 返回值: true 所有任务已完成, false 超时 virtual bool WaitAllTaskFinish(int timeoutMs = 0) override; // 查询状态 int GetThreadCount() const; // 当前线程总数 int GetIdleThreadCount() const; // 空闲线程数 int GetPendingTaskCount() const; // 等待队列中的任务数 private: // 任务执行完成回调(由工作线程在任务完成后调用) void _ExecFinish(void* pObject); private: typedef std::pair PendingTask; mutable std::mutex m_mutexPool; std::condition_variable m_cvIdle; // 空闲通知(配合 WaitAllTaskFinish) std::vector m_vetThread; // 所有线程 std::deque m_deqRecoveryThread; // 空闲线程回收队列 std::deque m_deqPendingTasks; // 等待执行的任务队列 int m_nMaxThreadCount; // 最大线程数 std::atomic m_bStop; // 停止标志 }; #endif // VRTHREADPOOL_H