61 lines
1.6 KiB
C++
61 lines
1.6 KiB
C++
#ifndef VRTHREAD_H
|
||
#define VRTHREAD_H
|
||
|
||
#include <thread>
|
||
#include <mutex>
|
||
#include <functional>
|
||
#include <atomic>
|
||
#include <condition_variable>
|
||
|
||
#include "IVrThreadPool.h"
|
||
|
||
typedef std::function<void (void *)> ExecFinishFunc;
|
||
|
||
class VrThread
|
||
{
|
||
public:
|
||
explicit VrThread(int index);
|
||
~VrThread();
|
||
|
||
// 初始化工作线程
|
||
int Init();
|
||
|
||
// 执行任务
|
||
// 返回值: VrThreadPoolError::Ok(0) 成功, 负值为错误码
|
||
int ExecTask(ThreadExecFunc fExecFunc, void* pParam,
|
||
ExecFinishFunc pExecFinishFunc, void* pFinishParam);
|
||
|
||
// 停止线程(设置停止标志并唤醒等待中的线程)
|
||
void Stop();
|
||
|
||
// 查询线程是否空闲(可以接受新任务)
|
||
bool IsIdle() const;
|
||
|
||
private:
|
||
void _ExecTask();
|
||
|
||
private:
|
||
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;
|
||
};
|
||
|
||
#endif // VRTHREAD_H
|