ThreadPool

感谢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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值