感谢Git大佬分享,源码在https://github.com/progschj/ThreadPool
为了方便自己理解,做了如下注释并再次记录
#ifndef THREAD_POOL_H
#define THREAD_POOL_H
#include <vector>
#include <queue>
#include <memory>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <functional>
#include <stdexcept>
#include <iostream>
class ThreadPool {
public:
ThreadPool(size_t);//构造函数
//往任务队列中添加任务
template<class F, class... Args>
auto enqueue(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type>;
~ThreadPool();//析构函数
private:
// need to keep track of threads so we can join them
// 工作线程数组,会在线程池初始化的时候就根据输出的尺寸生成
// 在没有接受到任务的时候,线程池中的线程会已知处于休眠状态
std::vector< std::thread > workers;
// the task queue
// 任务队列
// std::function<> 是通用多态函数包装器,是一个类模板,可以容纳除类非静态成员函数指针之外的所有可调用对象
// 类的非静态成员函数可以通过std::bind后再赋给包装器
std::queue< std::function<void()> > tasks;
// synchronization
std::mutex queue_mutex;//队列锁
std::condition_variable condition;//唤醒线程的状态变量
bool stop;//线程池结束信号
};
// the constructor just launches some amount of workers
inline ThreadPool::ThreadPool(size_t threads)
: stop(false)
{
// 创建给定数量的线程,用的是一个lambda表达式
for(size_t i = 0;i<threads;++i)
{
workers.emplace_back(
[this]
{
for(;;)
{
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(this->queue_mutex);
// 在没有任务的时候,所有的线程都会阻塞在这里
// 此处wait只有在当后面的那个调试是false的时候才会等待,后面的如果是true,此处不会等待
this->condition.wait(lock,
[this]{ return this->stop || !this->tasks.empty(); });
if(this->stop && this->tasks.empty())
return;
// 被唤醒后,取任务队列中的第一个
task = std::move(this->tasks.front());
this->tasks.pop();
}
// 执行任务
task();
}
}
);
}
}
// add new work item to the pool
// 将新的任务放到任务队列中
// 模板函数定义
template<class F, class... Args>
auto ThreadPool::enqueue(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type>//此处用于说明返回类型
{
using return_type = typename std::result_of<F(Args...)>::type;//result_of及后面的type用于获取F在输入状态后的返回值的类型
// 让传入的函数指针打包成共享指针
auto task = std::make_shared< std::packaged_task<return_type()> >(
std::bind(std::forward<F>(f), std::forward<Args>(args)...)
);
//获取task执行后的结果,保存到res中
std::future<return_type> res = task->get_future();
{
//加锁
std::unique_lock<std::mutex> lock(queue_mutex);
// don't allow enqueueing after stopping the pool
//当线程池停止的时候,不允许添加任务
if(stop)
throw std::runtime_error("enqueue on stopped ThreadPool");//终止,抛出异常
tasks.emplace([task](){ (*task)(); });//将任务指针放到队列中
}
//唤醒一个正在等待的线程,若没有线程在等待则不做任何动作
condition.notify_one();
return res;
}
// the destructor joins all threads
inline ThreadPool::~ThreadPool()
{
//加这个括号是为了作用于,unique_lock在作用域内有效,超出则自动解锁
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
// 唤醒所有的线程
condition.notify_all();
for(std::thread &worker: workers)
worker.join();
}
#endif