ThreadPool.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);
//! F&& f: 对可调用对象的右值引用,允许利用移动语义,T&&-右值引用。
//! Args&&... args: 可变数量的参数,使用完美转发来避免不必要的拷贝,
//! 同时支持左值和右值。
template<class F, class... Args>
//! std::future对象,其存储的类型为可调用对象调用结果的类型
//! ->:尾置返回类型,让返回类型依赖于函数参数的类型
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;
};
/***************************************************************************
函数名称: ThreadPool
功能描述: the constructor just launches some amount of workers
输入参数: threads,表示要创建并运行的工作线线程的数量
输出参数:
返 回 值:
作 者 : zhangsan
修改日期: 4/9/24 2:59 PM
修改记录1:// 修改历史记录,包括修改日期、修改者及修改内容
修改日期:
版 本 号:
修 改 人:
修改内容:
****************************************************************************/
inline ThreadPool::ThreadPool(size_t threads)
: stop(false)
{
//! 循环for(size_t i = 0; i < threads; ++i)遍历从0到threads(不包括threads),
//! 为每个工作线程创建一次迭代
f