#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>
using namespace std;
class ThreadPool {
public:
ThreadPool(size_t);
template<class F, class... Args>
auto enqueue(F&& f, Args&&... args)//表示引用,对虚拟类的引用,T&而不是T;
->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::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)//对类的内置参数进行初始化。stop=false;
{
for (size_t i = 0; i < threads; ++i)
workers.emplace_back(
[this] //后续才能调用内部参数,this表示实例本身所在的地址空间。//从这里开始,就是一个即将装入线程的函数
{
while (1)//让这4个线程会一直无限的开启,当有一个task进入时,线程装入task,运行task。然后又继续等待新的task。如果不用while,那么在执行一次task后,这个线程就关闭了
{
std::function<void()> task;//先封装一个task函数作为空线程。在实际使用中就会对task进行实例化,将实际要运行的线程装入。
{
std::unique_lock<std::mutex> lock(this->queue_mutex);
this->condition.wait(lock,
[this] { return this->stop || !this->tasks.empty(); });//lambda函数是阻塞条件,阻塞,直到当stop为true或者tasks不为空时,放开阻塞。
if (this->stop && this->tasks.empty()) {
return;
}
task = std::move(this->tasks.front());//会将tasks.front()的值移给task。
this->tasks.pop();//将task弹出
}//这个{}符号,保证unique_lock的生命周期只在这里有效
task();//执行线程
}
}//到这里结束,就是把一个函数当一个线程塞入到vector<thead> 中,相当于线程定义(std::thead t(func,参数1,参数2)),在上边的lambda函数就是func;
);
}
// 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;//推导出返回值类型
auto task = std::make_shared< std::packaged_task<return_type()> >(
std::bind(std::forward<F>(f), std::forward<Args>(args)...)//forward函数,对类型T进行完美转发,去定义f。
);//bind 函数,接受函数 f 和部分参数,返回currying后的匿名函数,譬如 bind(add, 4) 可以实现类似 add(4)的函数;
//将参数args传给函数f。函数将可调用对象和可调用对象的参数进行绑定,返回新的可调用对象
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)(); });//在tasks末尾推入
}
cout << "notify了" << endl;
condition.notify_one();
return res;
}
// the destructor joins all threads
inline ThreadPool::~ThreadPool()
{
{
cout << "调用析构" << endl;
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
condition.notify_all();
for (std::thread &worker : workers)
worker.join();
cout << "析构结束" << endl;
}
#endif
这里需要注意得是,对于lock_guard是RAII机制,会利用C++对象得生命周期自动化lock和unlock调用。所以管理临界区资源时,要设置包围{}。而unique_lock就没必要。
原文地址:添加链接描述