线程池,看这一篇就够了!

本文主要介绍如何设计一个高效通用的线程池。详细说明了一个线程池由哪几部分组成,最后通过100行C++代码实现一个高效通用的线程池。

1. 线程池的基础元素

  1. std::vector<std::thread> workers
  2. std::queue<std::function<void()>> tasks
  3. std::mutex queue_mutex
  4. std::condition_variable condition
  5. bool stop

2. 基础元素的说明

  1. workers:线程容器,用于从tasks队列中获取任务,并执行该任务
  2. tasks:任务队列,用于存储添加到线程池中的待执行任务
  3. queue_mutex:读写任务队列时的互斥锁,tasks队列是一个竞争资源,对tasks队列进行操作时需要保证互斥性
  4. condition:条件变量,用来监视资源是否可用(监视任务队列是否有任务和stop是否为true)
  5. stop:全局控制变量,用来控制是否可以往tasks队列中添加任务和队列为空时,线程池中的线程是否可以退出

3. condition的补充说明

  1. 当 std::condition_variable 对象的某个 wait 函数被调用的时候,它使用 std::unique_lock(通过 std::mutex 定义的) 来锁住当前线程。当前线程会一直被阻塞,直到另外一个线程在相同的 std::condition_variable 对象上调用了notify_one/notify_all 函数来唤醒当前线程
  2. 对于wait函数的pred参数,只有当 pred 条件为 false 时调用 wait() 才会阻塞当前线程,并且在收到其他线程的通知后只有当 pred 为 true 时才会被解除阻塞

4. C++实现

#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

5. 参考资料

  1. 100行实现线程池
  2. std::condition_variable 类介绍
posted @ 2020-02-22 16:31  wengle  阅读(643)  评论(0编辑  收藏  举报