C++简单易用线程池
线程模板类功能
- start 启动线程池
- stop 停止线程池
- setThreadCount 设置线程数量
- addTask 添加线程任务 (使用 std::function)
- threadSize 获取线程数量
- taskSize 获取任务队列数量
- workThreadSize 获取工作线程数
- leisureThreadSize 获取空闲线程数
#ifndef THREADPOOL_H
#define THREADPOOL_H
#include <thread>
#include <mutex>
#include <memory>
#include <map>
#include <list>
#include <atomic>
//线程状态
enum ET_STATUS {
INIT, //初始化状态
WAIT, //等待状态
RUN, //运行状态
STOP, //停止状态
};
typedef ET_STATUS TS; //线程状态
template<typename T>
class ThreadPool
{
private:
typedef std::function<void(T&)> Task;
public:
ThreadPool();
~ThreadPool();
void start(unsigned short thread_count = 0); //启动线程池
void stop(); //停止线程池
void setThreadCount(unsigned short threadCount); //设置线程数量
void addTask(const Task& task, T& data); //添加任务
int threadSize() const; //获取线程数量
int taskSize(); //获取任务队列数量
unsigned short workThreadSize() const;
unsigned short leisureThreadSize() const;
private:
ThreadPool(const ThreadPool&) {};
const ThreadPool& operator=(const ThreadPool&) {};
void threadLoop(); //执行方法
auto getTask(); //获取任务
void addThread(); //添加线程
TS findCurrentStatus(); //获取当前线程状态
void setCurrentStatus(TS ts); //设置当前线程状态
void management(); //线程管理
private:
bool m_isRun; // 线程池运行状态
unsigned short m_threadCount; //线程数量
const unsigned short MAX_THREAD_COUNT = 250; //最大线程数
const unsigned short DEFINE_THREAD_COUNT = 6; //默认线程数
std::atomic_int work_thread_count; //工作线程数
std::atomic_int leisure_thread_count; //空闲线程数
struct QueData {
QueData() {};
QueData(const Task& t, T& d) {
task = t;
data = d;
}
~QueData() {
task = NULL;
data = T();
}
Task task = NULL;
T data;
};
std::list<QueData> m_queueTask; //任务队列
typedef std::unique_ptr<std::thread> thread_prt;
struct thread_info {
thread_info(std::thread* th_ptr) {
thread_ = std::move(thread_prt(th_ptr));
id_ = th_ptr->get_id();
status_ = TS::INIT;
}
std::thr