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