- new thread pool (no stucks anymore)

This commit is contained in:
2020-05-08 17:05:56 +03:00
parent 0d69c26a13
commit 086581a2b1
2 changed files with 66 additions and 83 deletions

View File

@@ -0,0 +1,51 @@
#include "HL_ThreadPool.h"
thread_pool::thread_pool(size_t num_of_threads, const std::string& name)
{
this->name = name;
if (!num_of_threads)
num_of_threads = std::thread::hardware_concurrency();
for(size_t idx = 0; idx < num_of_threads; idx++)
this->workers.push_back(std::thread(&thread_pool::run_worker, this));
}
// Add new work item to the pool
void thread_pool::enqueue(const thread_pool::task& t)
{
{
std::unique_lock<std::mutex> lock(this->queue_mutex);
this->tasks.push(t);
}
this->condition.notify_one();
}
// the destructor joins all threads
thread_pool::~thread_pool()
{
{
std::unique_lock<std::mutex> lock(this->queue_mutex);
stop = true;
}
this->condition.notify_all();
for(std::thread &worker: workers)
worker.join();
}
void thread_pool::run_worker()
{
ThreadHelper::setName(this->name);
task t;
while(!this->stop)
{
{
std::unique_lock<std::mutex> lock(this->queue_mutex);
this->condition.wait(lock, [this]{return !this->tasks.empty() || this->stop;});
t = this->tasks.front();
this->tasks.pop();
}
t(); // function<void()> type
}
}