#include <iostream>
#include <mutex>
#include <future>
#include <thread>
#include <exception>
#include <functional>
#include <numeric>
#include <limits>
#include <queue>
using namespace std;
class CThreadPool
{
bool m_boolIsWorking = true;
std::mutex m_mtxWorkQueueMtx;
std::condition_variable m_cvWorkCv;
std::queue<std::function<void()>> m_queWorkQue;
std::vector<std::thread> m_vecThreadVec;
void WorkThread()
{
while (m_boolIsWorking)
{
std::unique_lock<std::mutex> lk(m_mtxWorkQueueMtx);
m_cvWorkCv.wait(lk, [this]() {return false == m_boolIsWorking || false == m_queWorkQue.empty();});
if (false == m_boolIsWorking)
return;
auto task = std::move(m_queWorkQue.front());
m_queWorkQue.pop();
try {task();}catch (...){}
}
}
public:
CThreadPool()
{
m_boolIsWorking = true;
auto size = std::thread::hardware_concurrency();
while (0 != size--)
m_vecThreadVec.push_back(std::thread(&CThreadPool::WorkThread, this));
}
~CThreadPool()
{
m_boolIsWorking = false;
std::unique_lock<std::mutex> lk(m_mtxWorkQueueMtx);
m_cvWorkCv.notify_all();
lk.unlock();
for (auto & th : m_vecThreadVec)
th.join();
}
void PutTask(std::function<void()> f)
{
std::unique_lock<std::mutex> lk(m_mtxWorkQueueMtx);
m_queWorkQue.push(std::move(f));
m_cvWorkCv.notify_one();
}
};
int main()
{
{
CThreadPool pool;
int a;
while (cin >> a)
{
if (0 == a)
break;
while (0 != a--)
{
pool.PutTask([]() {std::this_thread::sleep_for(std::chrono::seconds(1));cout << ".";});
}
}
}
int pause;
cin >> pause;
}
经典的线程池
最新推荐文章于 2020-03-15 00:20:06 发布