From a10e112e6436b30c9eb5ca2a82c94f83205bbc34 Mon Sep 17 00:00:00 2001 From: FernandoS27 Date: Tue, 6 Apr 2021 04:23:02 +0200 Subject: common/thread_worker: Fix data race --- src/common/thread_worker.cpp | 14 +++++++++++++- src/common/thread_worker.h | 5 +++++ 2 files changed, 18 insertions(+), 1 deletion(-) (limited to 'src/common') diff --git a/src/common/thread_worker.cpp b/src/common/thread_worker.cpp index f4d8bb0f0..fd130dfb4 100644 --- a/src/common/thread_worker.cpp +++ b/src/common/thread_worker.cpp @@ -8,9 +8,17 @@ namespace Common { ThreadWorker::ThreadWorker(std::size_t num_workers, const std::string& name) { + workers_queued.store(static_cast(num_workers), std::memory_order_release); const auto lambda = [this, thread_name{std::string{name}}] { Common::SetCurrentThreadName(thread_name.c_str()); + // TODO(Blinkhawk): Change the design, this is very prone to data races + // Wait for first request + { + std::unique_lock lock{queue_mutex}; + condition.wait(lock, [this] { return stop || !requests.empty(); }); + } + while (!stop) { UniqueFunction task; { @@ -26,7 +34,9 @@ ThreadWorker::ThreadWorker(std::size_t num_workers, const std::string& name) { requests.pop(); } task(); + work_done++; } + workers_stopped++; wait_condition.notify_all(); }; for (size_t i = 0; i < num_workers; ++i) { @@ -49,13 +59,15 @@ void ThreadWorker::QueueWork(UniqueFunction work) { { std::unique_lock lock{queue_mutex}; requests.emplace(std::move(work)); + work_scheduled++; } condition.notify_one(); } void ThreadWorker::WaitForRequests() { std::unique_lock lock{queue_mutex}; - wait_condition.wait(lock, [this] { return stop || requests.empty(); }); + wait_condition.wait( + lock, [this] { return workers_stopped >= workers_queued || work_done >= work_scheduled; }); } } // namespace Common diff --git a/src/common/thread_worker.h b/src/common/thread_worker.h index 7e2b04a07..12bbf5fef 100644 --- a/src/common/thread_worker.h +++ b/src/common/thread_worker.h @@ -11,6 +11,7 @@ #include #include +#include "common/common_types.h" #include "common/unique_function.h" namespace Common { @@ -29,6 +30,10 @@ private: std::condition_variable condition; std::condition_variable wait_condition; std::atomic_bool stop{}; + std::atomic work_scheduled{}; + std::atomic work_done{}; + std::atomic workers_stopped{}; + std::atomic workers_queued{}; }; } // namespace Common -- cgit v1.2.3