Refactored thread_pool_executor methods

This commit is contained in:
Bartek Kryza
2022-03-18 22:52:23 +01:00
parent c17a1cb1aa
commit 82737df05c
2 changed files with 93 additions and 81 deletions

View File

@@ -25,78 +25,20 @@
namespace clanguml::util {
class thread_pool_executor {
public:
thread_pool_executor()
: thread_pool_executor{0}
{
}
thread_pool_executor();
thread_pool_executor(unsigned int pool_size)
: done_{false}
{
if (pool_size == 0U)
pool_size = std::thread::hardware_concurrency();
thread_pool_executor(unsigned int pool_size);
for (auto i = 0U; i < pool_size; i++) {
threads_.push_back(
std::thread{&thread_pool_executor::worker, this});
}
}
~thread_pool_executor();
~thread_pool_executor() { stop(); }
std::future<void> add(std::function<void()> &&task);
std::future<void> add(std::function<void()> &&task)
{
std::unique_lock<std::mutex> l(tasks_mutex_);
std::packaged_task<void()> ptask{std::move(task)};
auto res = ptask.get_future();
tasks_.emplace_back(std::move(ptask));
l.unlock();
tasks_cond_.notify_one();
return res;
}
void stop()
{
done_ = true;
for (auto &thread : threads_) {
if (thread.joinable())
thread.join();
}
}
void stop();
private:
void worker()
{
try {
while (!done_) {
auto task = get();
void worker();
task();
}
}
catch (std::runtime_error &e) {
}
}
std::packaged_task<void()> get()
{
std::unique_lock<std::mutex> l(tasks_mutex_);
while (tasks_.empty()) {
if (done_)
throw std::runtime_error("Thread pool closing...");
tasks_cond_.wait_for(l, std::chrono::seconds(1));
}
auto res = std::move(tasks_.front());
tasks_.pop_front();
return res;
}
std::packaged_task<void()> get();
std::atomic_bool done_;