上一篇博客讲述了一些线程池的知识。
但是C++11让线程变得更加简单,关于C++11线程方面的知识之前也有过介绍。
今天就介绍一个使用C++11写的简单的一个线程池,thread pool.
github地址:
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>
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;
};