2026-06-20 23:36:24 +08:00
|
|
|
|
#ifndef VRTHREAD_H
|
|
|
|
|
|
#define VRTHREAD_H
|
2026-03-28 10:49:55 +08:00
|
|
|
|
|
|
|
|
|
|
#include <thread>
|
|
|
|
|
|
#include <mutex>
|
|
|
|
|
|
#include <functional>
|
2026-06-20 23:36:24 +08:00
|
|
|
|
#include <atomic>
|
|
|
|
|
|
#include <condition_variable>
|
2026-03-28 10:49:55 +08:00
|
|
|
|
|
|
|
|
|
|
#include "IVrThreadPool.h"
|
|
|
|
|
|
|
|
|
|
|
|
typedef std::function<void (void *)> ExecFinishFunc;
|
|
|
|
|
|
|
|
|
|
|
|
class VrThread
|
|
|
|
|
|
{
|
|
|
|
|
|
public:
|
2026-06-20 23:36:24 +08:00
|
|
|
|
explicit VrThread(int index);
|
|
|
|
|
|
~VrThread();
|
2026-03-28 10:49:55 +08:00
|
|
|
|
|
2026-06-20 23:36:24 +08:00
|
|
|
|
// 初始化工作线程
|
2026-03-28 10:49:55 +08:00
|
|
|
|
int Init();
|
|
|
|
|
|
|
|
|
|
|
|
// 执行任务
|
2026-06-20 23:36:24 +08:00
|
|
|
|
// 返回值: VrThreadPoolError::Ok(0) 成功, 负值为错误码
|
|
|
|
|
|
int ExecTask(ThreadExecFunc fExecFunc, void* pParam,
|
|
|
|
|
|
ExecFinishFunc pExecFinishFunc, void* pFinishParam);
|
|
|
|
|
|
|
|
|
|
|
|
// 停止线程(设置停止标志并唤醒等待中的线程)
|
|
|
|
|
|
void Stop();
|
|
|
|
|
|
|
|
|
|
|
|
// 查询线程是否空闲(可以接受新任务)
|
|
|
|
|
|
bool IsIdle() const;
|
2026-03-28 10:49:55 +08:00
|
|
|
|
|
|
|
|
|
|
private:
|
|
|
|
|
|
void _ExecTask();
|
|
|
|
|
|
|
|
|
|
|
|
private:
|
2026-06-20 23:36:24 +08:00
|
|
|
|
int m_nIndex; // 线程索引
|
|
|
|
|
|
std::atomic<bool> m_bStarted; // 工作线程是否已启动
|
|
|
|
|
|
std::atomic<bool> m_bStop; // 停止标志
|
|
|
|
|
|
|
|
|
|
|
|
// 是否有待执行的任务(原子变量,允许无锁快速查询)
|
|
|
|
|
|
std::atomic<bool> m_bHasTask;
|
|
|
|
|
|
ThreadExecFunc m_fExecFunc;
|
|
|
|
|
|
void* m_pParam;
|
|
|
|
|
|
|
|
|
|
|
|
// 任务完成回调(由 m_mutexExec 保护)
|
|
|
|
|
|
ExecFinishFunc m_fFinishFunc;
|
|
|
|
|
|
void* m_pFinishParam;
|
|
|
|
|
|
|
|
|
|
|
|
// 同步原语
|
|
|
|
|
|
std::mutex m_mutexExec;
|
|
|
|
|
|
std::condition_variable m_condExec; // 任务通知
|
|
|
|
|
|
std::condition_variable m_cvStarted; // 线程启动完成通知
|
|
|
|
|
|
|
|
|
|
|
|
// 工作线程(拥有所有权,析构时 join)
|
|
|
|
|
|
std::thread m_execThread;
|
2026-03-28 10:49:55 +08:00
|
|
|
|
};
|
|
|
|
|
|
|
2026-06-20 23:36:24 +08:00
|
|
|
|
#endif // VRTHREAD_H
|