GrabBag/Module/ThreadPool/_Inc/VrThreadPool.h

53 lines
1.9 KiB
C
Raw Normal View History

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