在实现线程池之前呢,我们还是要先了解一下线程池的组成:
1、线程池管理器
创建一定数量的线程,启动线程,调配任务,管理着线程池。
append()添加任务.

2、工作线程
线程池中线程,在线程池中等待并执行分配的任务.
这里选用条件变量实现等待与通知机制.

3、任务接口
添加任务的接口,以供工作线程调度任务的执行。

4、任务队列
用于存放没有处理的任务。提供一种缓冲机制
同时任务队列具有调度功能,这里选用queue作为任务队列

代码如下:参考链接:https://www.cnblogs.com/Tattoo-Welkin/p/10335254.html

#include<iostream>
#include<vector>
#include<queue>
#include<stdexcept>
#include<mutex>
#include<memory>
#include<condition_variable>
#include<thread>

using namespace std;

const int MAX_THREAD = 100;

template<class T>
class ThreadPool
{
    public:
        ThreadPool(int number = 1);
        ~ThreadPool();
        bool append(T* task);

    private:
        static void *work(void *arg);
        void run();

    private:
        vector<thread> workthreads;
        queue<T *> tasks;
        mutex queue_mutex;
        condition_variable condition;
        bool stop;
};

template<class T>
ThreadPool<T>::ThreadPool(int number):stop(false)
{
    if(number <=0 || number > MAX_THREAD)
        throw exception();

    for(int i = 0; i < number; ++i)
    {
        cout << "create the " << i << "thread" << endl;

        workthreads.emplace_back(work, this); 
    }
}

template<class T>
ThreadPool<T>::~ThreadPool()
{
    unique_lock<std::mutex> lock(queue_mutex);
    stop = true;

    condition.notify_all();

    for(auto &ww: workthreads)
        ww.join();
}

template<class T>
bool ThreadPool<T>::append(T* task)
{
    queue_mutex.lock();
    tasks.push(task);
    queue_mutex.unlock();
    condition.notify_one();

    return true;
}

template<class T>
void* ThreadPool<T>::work(void *arg)
{
    ThreadPool* pool = (ThreadPool*)arg;
    pool->run();

    return pool;
}

template<class T>
void ThreadPool<T>::run()
{
    while(!stop)
    {
        unique_lock<std::mutex> lk(this->queue_mutex);
        this->condition.wait(lk, [this] { return !this->tasks.empty();});

        if(this->tasks.empty())
        {
            continue;
        }
        else
        {
            T* request = tasks.front();
            tasks.pop();

            if(request)
                request->process();
        }

    }
}

class Task
{
    public:
        void process()
        {
            cout << "run ......" << endl;
        }
};

int main()
{
    ThreadPool<Task> pool(6);

    while(1)
    {
        Task* tt = new Task();

        pool.append(tt);

        delete tt;
    }

    return 0;
}

测试程序运行结果:
图片说明