线程池的C++实现
这个代码不是本人原创,而是网上的代码 https://github.com/progschj/ThreadPool
1. 大致思路
线程池目的是减少创建销毁线程的开销。大致的思想是生产者消费者模型,主线程为生产者,负责往任务队列中加新任务,如果没有新任务则发出结束信号。消费者线程不停检查任务队列和结束信号,如果有任务则取一个处理。没有则等待,如果检测到结束信号则退出。
剩下的问题是,消费者处理完任务的返回值如何存放。在这个实现中使用了std::future用于等待和接收任务的返回值。我们先来看一下std::future是如何用作等待函数的返回值的
#include <iostream>
#include <future>
int main() {
// 封装一下函数
std::packaged_task<int()> task([]{ return 7; });
//获取返回值place_holder
std::future<int> f1 = task.get_future();
//执行函数
task();
f1.wait();
//打印 7
std::cout << f1.get() << '\n';
return 0;
}
直到task();之前,函数都没有执行,只是将函数体和函数返回值作了分离:task封装了函数体,f1封装了返回值。按照这个思路,生产者将task的函数体放入到任务队列中,供消费者调用,而将所有任务的返回值作为std::future类型放入到一个数组中,供外部程序访问即可。
2. 代码注释
现在可以看代码并思考一些细节了
//ThreadPool.h
#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>
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:
// 消费者线程
std::vector< std::thread > workers;
//任务队列
std::queue< std::function<void()> > tasks;
//互斥量
std::mutex queue_mutex;
std::condition_variable condition;
//停止信号,如果为true,则表示没有新的任务
bool stop;
};
//构造函数,分配threads个消费者线程
inline ThreadPool::ThreadPool(size_t threads)
: stop(false)
{
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);
//检查任务队列和停止信号,如果有任务或者有停止信号则往下执行,否则释放锁让其他线程可以访问锁,并将自己阻塞
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();
}
}
);
}
//生产者添加一个新的任务,其函数类型为F,参数类型为Args,这里的具名右值引用是为了统一const T &和T &两种形参,算是形参的万能模版
template<class F, class... Args>
auto ThreadPool::enqueue(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type>
{
//std::result_of<F(Args...)>::type是函数的返回值类型
using return_type = typename std::result_of<F(Args...)>::type;
//下面std::forward的作用是为了保持具名右值引用,否则原来的T &&传入到task时会变成T &
//使用bind让所有形参消失,从而统一了任务的函数类型
//使用shared_ptr是因为后面要复制这个指针到任务队列中
auto task = std::make_shared< std::packaged_task<return_type()> >(
std::bind(std::forward<F>(f), std::forward<Args>(args)...)
);
//分离返回值和函数体
std::future<return_type> res = task->get_future();
{
std::unique_lock<std::mutex> lock(queue_mutex);
//如果已经停止,则不能加入新的任务
if(stop)
throw std::runtime_error("enqueue on stopped ThreadPool");
//这里*task就是std::packaged_task<return_type()>,(*task)() = f(args...),而tasks是std::function,封装了这段执行的代码,真正的执行是在消费者线程中
tasks.emplace([task](){ (*task)(); });
}
//通知一个消费者线程,有新任务了
condition.notify_one();
return res;
}
inline ThreadPool::~ThreadPool()
{
{
std::unique_lock<std::mutex> lock(queue_mutex);
//没有更多任务了
stop = true;
}
//通知所有消费者线程,拿到任务的执行剩下的任务,没有任务的退出
condition.notify_all();
//结束所有消费者线程
for(std::thread &worker: workers)
worker.join();
}
#endif
来看调用代码
#include <iostream>
#include <vector>
#include <chrono>
#include "ThreadPool.h"
int main()
{
//4个消费者,没有任务时,处于阻塞状态
ThreadPool pool(4);
//任务返回值
std::vector< std::future<int> > results;
//8个任务
for(int i = 0; i < 8; ++i) {
results.emplace_back(
pool.enqueue([i] {
std::cout << "hello " << i << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "world " << i << std::endl;
return i*i;
})
);
}
//获取返回值
for(auto && result: results)
std::cout << result.get() << ' ';
std::cout << std::endl;
return 0;
}
应该来说还是很清楚简单的。