From a7b41c49fe05719c58091779bd500b1e5bb115ac Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Felix=20Kohlgr=C3=BCber?= <felix.kohlgrueber@gmail.com>
Date: Wed, 22 Jun 2022 11:50:19 +0200
Subject: [PATCH] fix for spurious wakeups in scoped_timer (#6102)

---
 src/util/scoped_timer.cpp | 28 ++++++++++++++--------------
 src/util/scoped_timer.h   |  2 ++
 2 files changed, 16 insertions(+), 14 deletions(-)

diff --git a/src/util/scoped_timer.cpp b/src/util/scoped_timer.cpp
index b5968cc06..ce1b14a23 100644
--- a/src/util/scoped_timer.cpp
+++ b/src/util/scoped_timer.cpp
@@ -80,27 +80,20 @@ scoped_timer::scoped_timer(unsigned ms, event_handler * eh) {
         return;
 
     workers.lock();
-    bool new_worker = false;
     if (available_workers.empty()) {
+        // start new thead
         workers.unlock();
         s = new scoped_timer_state;
-        new_worker = true;
         ++num_workers;
-        s->work = WORKING;
-    }
-    else {
-        s = available_workers.back();
-        available_workers.pop_back();
-        s->work = WORKING;
-        workers.unlock();
-    }
-    s->ms = ms;
-    s->eh = eh;
-    s->m_mutex.lock();
-    if (new_worker) {
+        init_state(ms, eh);
         s->m_thread = std::thread(thread_func, s);
     }
     else {
+        // re-use existing thread
+        s = available_workers.back();
+        available_workers.pop_back();
+        init_state(ms, eh);
+        workers.unlock();
         s->cv.notify_one();
     }
 }
@@ -148,3 +141,10 @@ void scoped_timer::finalize() {
     num_workers = 0;
     available_workers.clear();
 }
+
+void scoped_timer::init_state(unsigned ms, event_handler * eh) {
+    s->ms = ms;
+    s->eh = eh;
+    s->m_mutex.lock();
+    s->work = WORKING;
+}
diff --git a/src/util/scoped_timer.h b/src/util/scoped_timer.h
index dfd97810c..2f6875d36 100644
--- a/src/util/scoped_timer.h
+++ b/src/util/scoped_timer.h
@@ -29,6 +29,8 @@ public:
     ~scoped_timer();
     static void initialize();
     static void finalize();
+private:
+    void init_state(unsigned ms, event_handler * eh);
 };
 
 /*