cpputil/src/threadpool.cpp

43 lines
767 B
C++

#include "threadpool.h"
threadpool::threadpool() : threadpool(std::thread::hardware_concurrency())
{
}
threadpool::threadpool(std::size_t concurrency) : _concurrency(concurrency), _enabled(true)
{
for (std::size_t i = 0; i < _concurrency; ++i)
{
_workers.push_back(std::thread(&threadpool::worker_func, this));
}
}
threadpool::~threadpool()
{
_enabled = false;
_cv.notify_all();
for (std::size_t i = 0; i < _workers.size(); ++i)
{
_workers[i].join();
}
}
void threadpool::worker_func()
{
while (_enabled)
{
std::unique_lock<std::mutex> lock(_mutex);
_cv.wait(lock, [this] { return (!_queue.empty() || !_enabled); });
if (_queue.empty() && !_enabled)
return;
auto func = _queue.front();
_queue.pop();
lock.unlock();
func();
}
}