Fix threadpool::wait - wait for finished tasks as well, not just empty task queue

This commit is contained in:
Nikita Lisitsa 2020-09-30 16:20:48 +03:00
parent 5079bcd127
commit 7b9e042842
2 changed files with 19 additions and 0 deletions

View file

@ -7,6 +7,8 @@
#include <future>
#include <vector>
#include <string>
#include <mutex>
#include <condition_variable>
namespace psemek::util
{
@ -19,6 +21,7 @@ namespace psemek::util
threadpool(std::string const & name, std::size_t thread_count)
: name(name)
, working_count_{0}
{
start(thread_count);
}
@ -49,12 +52,19 @@ namespace psemek::util
void wait()
{
tasks_queue.wait();
std::unique_lock lock{working_count_mutex_};
working_count_cv_.wait(lock, [this]{ return working_count_ == 0; });
}
private:
std::string const name;
std::vector<util::thread> threads;
util::synchronized_queue<movable_function<void()>> tasks_queue;
std::size_t working_count_;
std::mutex working_count_mutex_;
std::condition_variable working_count_cv_;
};
}

View file

@ -21,7 +21,16 @@ namespace psemek::util
if (!task)
break;
{
std::lock_guard lock{working_count_mutex_};
++working_count_;
}
task();
{
std::lock_guard lock{working_count_mutex_};
--working_count_;
}
working_count_cv_.notify_all();
}
});
}