SIMOrthoProgram-Orth_GF3-Strip/PSTM_simulation_windows2021.../PSTM_simulation_windows/threadpool.hpp

103 lines
2.5 KiB
C++
Raw Normal View History

#ifndef THREADPOOL_HPP
#define THREADPOOL_HPP
#include <atomic>
#include <condition_variable>
#include <functional>
#include <iostream>
#include <memory> //unique_ptr
#include <queue>
#include <stdexcept>
#include <thread>
#include <vector>
typedef std::function<void(void)> Task;
class ThreadPool {
public:
/**
* @brief ThreadPool
* @param number[in]线 *线
* @param
* emptyQuit[in]线退falsetruestartwaite
*/
ThreadPool(int number = 1, bool emptyQuit = false);
~ThreadPool();
/**
* @brief append task_queue<T *>
* @param task
* @return
*/
bool append(Task task);
/**
* @brief start
*/
void start();
/**
* @brief stop
*/
void stop();
/**
* @brief waiteFinish ,退
*/
void waiteFinish();
/**
* @brief
*/
int taskNum();
private:
/**
* @brief worker 线
* @param arg
* @return
*/
static void *worker(void *arg);
/**
* @brief run 线,
*/
void run();
/**
* @brief stopThreadGroup 线
*/
void stopThreadGroup();
/**
* @brief startThread 线
*/
void startThread();
/**
* @brief waiteThreadFinish 线
*/
void waiteThreadFinish();
/**
* @brief notEmpty
* @return
*/
bool notEmpty();
private:
std::vector<std::thread *> m_WorkThreads; /*工作线程*/
std::queue<Task> m_TasksQueue; /*任务队列*/
std::mutex m_QueueMutex;
std::condition_variable m_Condition; /*必须与unique_lock配合使用*/
std::recursive_mutex m_DataMutex; //数据锁
std::atomic_bool m_StopFlag; //是否停止标志
std::once_flag m_CallStopSlag;
std::once_flag m_CallStartSlag;
std::once_flag m_CallWaiteFinisFlag;
int m_ThreadNum; //线程数
std::atomic_bool m_EmptyQuit; //无任务退出模式,改模式先添加任务,再启动
std::atomic_bool m_JoinFlag; //线程是否Join
std::atomic_bool m_EmptyQuitWaite;//开始退出等待
std::atomic_int m_QuitNum;//退出的线程计数
};
typedef std::shared_ptr<ThreadPool> ThreadPoolPtr;
#endif // THREADPOOL_HPP