基于C++11的线程池实现


前端时间偶然在github上看到了一个非常精炼的 C++11线程池实现。作者用不到100行的代码实现了一个简单的线程池,且使用了较多C++11的新特性。于是便想着自己也来动手看看,思路上基本是借鉴原版,但会加入一些自己的想法和尝试,同时先避免对复杂语法的运用以理解线程池为首要目的。由于个人能力有限,如果代码中有明显bug欢迎指正,一起交流进步。

线程池基本组成

在贴源码之前先介绍一下线程池的基本组成,线程池一般由两种角色构成:多个工作线程和一个阻塞队列。

  • 工作线程
    工作线程是一组已经处在运行中的线程,它们不断地向阻塞队列中领取任务执行。
  • 阻塞队列
    阻塞队列用于存储工作线程来不及处理的任务。当工作线程都在执行任务时,到来的新任务就只能暂时在阻塞队列中存储。

一张图片便可以很直观的展示线程池:
线程池

源码和分析

ThreadPool.h:

#ifndef _THREAD_POOL_H
#define _THREAD_POOL_H

#include <vector>
#include <thread>
#include <mutex>
#include <functional>
#include <queue>
#include <future>
#include <memory>
#include <condition_variable>


class ThreadPool
{
    using Task = std::function<void()>;
public:
    ThreadPool(size_t num);
    ~ThreadPool();
    void entry();
    void shutdown();
    template <class Function,class... Args>
    // add_task相当于是对一个通用函数包装器的改造,不同点在于通用包装器的返回值可以return,而这里添加的task还未被执行
    // 需要等到将来工作线程来取,因此其返回类型的实现就需要用到std::future和std::packaged_task
    auto add_task(Function &&f, Args&&... args) -> std::future<decltype(f(std::forward<Args>(args)...))> 
    {
        using return_type = decltype(f(std::forward<Args>(args)...));
        // 通过std::bind()构造出一个void()可调用对象
        auto fun = std::bind(std::forward<Function>(f), std::forward<Args>(args)...);
        // 通过packaged_task获取一个异步操作的返回值,返回值也就是fun()也就是f(std::forward<Args>(args)...)的返回值
        auto task = std::make_shared<std::packaged_task<return_type()>>(fun);
        auto res = task->get_future();
        {
            std::unique_lock<std::mutex> lock(task_mutex);
            tasks.emplace([task]{(*task)();});
        }

        cond.notify_one();
        return res;
    }

private:
    std::vector<std::thread> threads;
    std::condition_variable cond;
    bool stop;
    std::queue<Task> tasks;// task排队应该先进先出,所以用队列
    std::mutex task_mutex;
};

#endif

ThreadPool.cc:

#include <iostream>
#include "ThreadPool.h"

using namespace std;

ThreadPool::ThreadPool(size_t num):stop(false)
{
    for(int i=0;i<num;++i)
        threads.emplace_back(&ThreadPool::entry,this);
}

void ThreadPool::entry()
{
    while(1)
    {
        unique_lock<mutex> lock(task_mutex);
        // 当任务队列为空且线程池正常状态时才会阻塞,被唤醒可能是由于有新任务到来或者是线程池准备停止
        cond.wait(lock,[this]{return this->stop||!this->tasks.empty();});
        // 如果是线程池停止,则退出子线程
        if(stop)
            return;

        // 否则就从任务队列中取最靠前的一个任务进行执行,并将任务出队
        Task cur_task = std::move(tasks.front());
        tasks.pop();
        lock.unlock();// task取出后就可以解锁
        cur_task();
    }
}

ThreadPool::~ThreadPool()
{
    cout<<"delete pool!"<<endl;
    if(!stop)
        shutdown();
}

void ThreadPool::shutdown()
{
    // 修改stop为true并通知所有线程池中的线程
    {
        unique_lock<mutex> lock(task_mutex);
        stop = true;
    }
    cond.notify_all();
    // 同时等待子线程执行完成
    for(auto &th: threads)
        th.join();
}

测试代码
main.cc:

#include <iostream>
#include <chrono>
#include "ThreadPool.h"

using namespace std;

int main()
{

    ThreadPool pool(4);
    std::vector< std::future<int> > results;

    for(int i = 0; i < 8; ++i) {
        results.emplace_back(// std::future不能复制,所以这里必须用emplace_back原地构造
            pool.add_task([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() << ' ';
    // .get()会阻塞直到获取到结果,如果shutdown放到get之前则get会一直阻塞
    pool.shutdown();
    std::cout << std::endl;
    
    return 0;
}

其中的一些关键点分析:

  1. 基本工作流程:线程池构造函数时创建n个线程,此时任务队列为空,所以这些线程都在阻塞状态,等到往任务队列中添加task,工作线程则取走task并执行。
  2. 线程池的退出由用户控制,提供了stop接口供用户停止,停止线程时会等待正在执行task的工作线程执行完成再回收。
  3. 代码的主要实现就是entry()和add_task(),前者实现了等待取task的逻辑,后者实现了异步执行task且支持各种类型的函数形式。其中关于add_task(),如注释所说相当于是对一个通用函数包装器的改造,不同点在于通用包装器的返回值可以return,而这里添加的task还未被执行需要等到将来工作线程来取。
  4. 注意std::future是不能拷贝的,所以如果要放到vector中必须原地构造
    先来看一下通用函数包装器的实现:
template <class Function,class... Args>
auto GeneralFunWrapper(Function &&f, Args&&... args) -> decltype(f(std::forward<Args>(args)...))
{
    return f(std::forward<Args>(args)...);
}

或者换一种实现方式,虽然就包装器来说多此一举但是对于向add_task的转化就更直观:

template <class Function,class... Args>
auto GeneralFunWrapper(Function &&f, Args&&... args) -> decltype(f(std::forward<Args>(args)...))
{
    auto fun = std::bind(std::forward<Function>(f),std::forward<Args>(args)...);
    return fun();
}

针对以上代码做基础修改:

  • 返回类型改为future
  • 需要将Function类型再封装为void()形式以适配Task
  • 直接执行改为放入task队列
  • 加入队列后唤醒线程池中的一个线程

参考

[1] A simple C++ 11 Thread Pool implementation
[2] 《深入应用C++ 11》by 祈宇

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值