//todo
/*
[root@Slave02 thread]# g++ thread_pool.cpp -o thread_pool -g -Wall -std=gnu++11 -lpthread;./thread_pool
Hello ThreadPool
class Test2 Hello world,0
Current thread id: 140287557768960, global function test_task str: Hello world
class Test Hello world,0
第一批 4 个任务完成,wait_limit_task exit
class Test Hello world,1
class Test Hello world,0
class Test Hello world,2
第二批 3 个任务完成,wait_limit_task exit
class Test2 Hello world,2
class Test2 Hello world,3
class Test2 Hello world,4
class Test2 Hello world,5
class Test2 Hello world,0
class Test2 Hello world,1
第三批 6 个任务完成,wait_limit_task exit
##############END#################
*/
#ifndef _THREAD_POOL_INCLUDE_H
#define _THREAD_POOL_INCLUDE_H
#include <cassert>
#include <cstdint>
#include <iostream>
#include <sstream>
#include <vector>
#include <queue>
#include <string>
#include <algorithm>
#include <functional>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <type_traits>
using namespace std;
class CThread_Pool
{
private:
using work_thread_ptr_t = std::shared_ptr<std::thread>;
using task_t = std::function<void ()>;
public:
~CThread_Pool()
{
stop();
}
//初始化指定线程池内线程数
void init_thread_num(uint32_t num)
{
is_stop_threadpool_.store(false);
limit_task_num_.store(0);
if (num <= 0 || num > MAX_THREAD_SIZE)
{
std::string str = "Number of threads in the range of 1 to " + std::to_string(MAX_THREAD_SIZE);
throw std::invalid_argument(str);
}
for (uint32_t i = 0; i < num; ++i)
{
work_thread_ptr_t t = std::make_shared<std::thread>(std::bind(&CThread_Pool::run_task, this));
thread_vec_.emplace_back(t);
}
}
//等待指定执行的任务结束
void wait_limit_task()
{
// 线程池循环取任务
std::unique_lock<std::mutex> locker(limit_task_);