ClickHouse/libs/libcommon/src/ThreadPool.cpp

115 lines
2.4 KiB
C++
Raw Normal View History

#include <common/ThreadPool.h>
2016-09-26 10:15:33 +00:00
#include <iostream>
2016-08-13 05:29:53 +00:00
ThreadPool::ThreadPool(size_t m_size)
: m_size(m_size)
2016-08-13 05:29:53 +00:00
{
threads.reserve(m_size);
for (size_t i = 0; i < m_size; ++i)
threads.emplace_back([this] { worker(); });
2016-08-13 05:29:53 +00:00
}
void ThreadPool::schedule(Job job)
{
{
std::unique_lock<std::mutex> lock(mutex);
has_free_thread.wait(lock, [this] { return active_jobs < m_size || shutdown; });
if (shutdown)
return;
jobs.push(std::move(job));
++active_jobs;
}
has_new_job_or_shutdown.notify_one();
2016-08-13 05:29:53 +00:00
}
void ThreadPool::wait()
{
{
std::unique_lock<std::mutex> lock(mutex);
has_free_thread.wait(lock, [this] { return active_jobs == 0; });
if (first_exception)
{
std::exception_ptr exception;
std::swap(exception, first_exception);
std::rethrow_exception(exception);
}
}
2016-08-13 05:29:53 +00:00
}
ThreadPool::~ThreadPool()
{
{
std::unique_lock<std::mutex> lock(mutex);
shutdown = true;
}
2016-08-13 05:29:53 +00:00
has_new_job_or_shutdown.notify_all();
2016-08-13 05:29:53 +00:00
for (auto & thread : threads)
thread.join();
2016-08-13 05:29:53 +00:00
}
size_t ThreadPool::active() const
{
std::unique_lock<std::mutex> lock(mutex);
return active_jobs;
2016-08-13 05:29:53 +00:00
}
void ThreadPool::worker()
{
while (true)
{
Job job;
bool need_shutdown = false;
{
std::unique_lock<std::mutex> lock(mutex);
has_new_job_or_shutdown.wait(lock, [this] { return shutdown || !jobs.empty(); });
need_shutdown = shutdown;
if (!jobs.empty())
{
job = std::move(jobs.front());
jobs.pop();
}
else
{
return;
}
}
if (!need_shutdown)
{
try
{
job();
}
catch (...)
{
{
std::unique_lock<std::mutex> lock(mutex);
if (!first_exception)
first_exception = std::current_exception();
shutdown = true;
--active_jobs;
}
has_free_thread.notify_all();
has_new_job_or_shutdown.notify_all();
return;
}
}
{
std::unique_lock<std::mutex> lock(mutex);
--active_jobs;
}
has_free_thread.notify_all();
}
2016-08-13 05:29:53 +00:00
}