c++模板线程池解读

前言

本篇文章是我个人在阅读一个模板线程池适合遇到的困惑,了解c++11一些特性后总算是能看懂了,虽然C++11新特性不难,但是结合模板用起来会比较蒙的。

线程池代码

线程池代码来自github上,链接在这里

#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:
    // 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)
{
    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();
                }
            }
        );
}

// 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)...)
        );
        
    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()
{
    {
        std::unique_lock<std::mutex> lock(queue_mutex);
        stop = true;
    }
    condition.notify_all();
    for(std::thread &worker: workers)
        worker.join();
}

#endif

分部解读

关于线程池实现原理和锁之类的就不说了,比较简单,主要说说模板这块。

声明

    template<class F, class... Args>
    auto enqueue(F&& f, Args&&... args) 
        -> std::future<typename std::result_of<F(Args...)>::type>;

声明这里我第一次看直接蒙蔽,首先我们从第一行开始看吧。

template<class F, class... Args>

class… Args 意味着这里使用了一个c++11的新特性变长实参,顾名思义就是使用的时候可以带很多个参数。详细的可以看变长实参参考手册

auto enqueue(F&& f, Args&&... args) 

这里的F&& f 和Args&&… args使用了右值引用,是为了使std::forward转发实参,转发引用参考手册

-> std::future<typename std::result_of<F(Args...)>::type>;

函数返回值是一个future对象,future是c++提供的异步操作结果的东西,future对象的类型使用result_of来帮助获取,result_of的主要作用是在编译的时候推导返回类型。两个可以参考手册future手册result_of手册

定义

定义也是主要看下enqueue函数

// 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)...)
        );
        
    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;
}

这里主要是

    auto task = std::make_shared< std::packaged_task<return_type()> >(
            std::bind(std::forward<F>(f), std::forward<Args>(args)...)
        );

这一段对参数传进来的函数进行一个包装。这里task是一个智能指针,是一个用bind将函数和参数绑定的对象,其中参数使用forward进行转发。

接着就是加锁,条件变量唤醒线程争夺任务,就没啥的了。

顺带一提

tasks.emplace([task](){ (*task)(); });

这里是用lambda表捕获task,然后直接运行。lambda真的好用。


版权声明:本文为ninesnow_c原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。