C++11 线程池

#include <cstdlib>
#include <string>
#include <iostream>
#include <memory>
#include <thread>
#include <vector>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include "boost/any.hpp"
using namespace std;

static const int MAX_TASK_NUM = 10;
class TP
{
public:
    TP() :m_tNum(0), m_busyCount(0), m_isFull(false)
    {

    }
    void init(int nTh)
    {

        for (int i = 0; i < nTh; ++i)
        {
            thread th(&TP::run, this);
            m_ths.emplace_back(std::move(th));
        }

    }
    void run()
    {
        while (true)
        {
            int i = 0;
            {
                unique_lock<mutex> ul(m_lockTaskPack);
                m_cvTaskPack.wait(ul, [this] {return !m_taskPack.empty(); });

                i = m_taskPack.front();
                m_taskPack.pop();
                m_busyCount++;
                cout << "one task pop, notify task queue, current queue size:" << m_taskPack.size()
                    << "thread id:" << this_thread::get_id() << endl;
                m_cvTaskPackQueue.notify_one();
            }
            this_thread::sleep_for(chrono::seconds(i));
            cout << "finish task:[" << i << "]" << endl;
            m_busyCount--;
        }
    }
    void addTask(int task)
    {
        unique_lock<mutex> ul(m_lockTaskPack);

        cout << "start wait queue not full" << endl;
        m_cvTaskPackQueue.wait(ul, [this]() {return !(m_taskPack.size() == MAX_TASK_NUM); });
        cout << "end wait queue not full" << endl;
        m_taskPack.push(task);
        cout << "queue size:[" << m_taskPack.size() << "], "
            << "current busy thread:[" << m_busyCount << "], "
            << "added task:[" << task << "]" << endl;
        m_cvTaskPack.notify_one();
    }

    void stop()
    {
        for (auto&& itr : m_ths)
        {
            itr.join();
        }
    }
private:

private:
    int m_tNum;
    vector<thread> m_ths;                   // 线程池
    mutex m_lockTaskPack;                   // 任务队列锁
    condition_variable m_cvTaskPack;        // 线程池等待条件,即队列空时线程等待获取任务
    condition_variable m_cvTaskPackQueue;   // 任务队列等待条件,即队列满时阻塞添加任务,等待线程池中有空闲线程
    bool m_isFull;
    atomic_int m_busyCount;                 // 工作中的线程数量
    queue<int> m_taskPack;                  // 任务队列
};
int main()
{
    TP tp;
    tp.init(5);
    int i = 10;
    while (true)
    {
        tp.addTask((11 + 1));
        ++i;
        this_thread::sleep_for(chrono::seconds(1));
    }
    cin.get();
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值