C++11 线程池实现-ThreadPool

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值