#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();
}