From f3cd7d646d021a02d6d1dbc6a419ec22668b5158 Mon Sep 17 00:00:00 2001 From: Nuno Lopes Date: Thu, 21 Feb 2019 10:42:42 +0000 Subject: [PATCH] further simplifications to scoped_timer --- src/util/scoped_timer.cpp | 33 +++++++++++++-------------------- 1 file changed, 13 insertions(+), 20 deletions(-) diff --git a/src/util/scoped_timer.cpp b/src/util/scoped_timer.cpp index e3b96fa15..58416289a 100644 --- a/src/util/scoped_timer.cpp +++ b/src/util/scoped_timer.cpp @@ -26,39 +26,33 @@ Revision History: struct scoped_timer::imp { - event_handler * m_eh; +private: std::thread m_thread; std::timed_mutex m_mutex; - unsigned m_ms; - static void* thread_func(imp * st) { - auto end = std::chrono::steady_clock::now() + std::chrono::milliseconds(st->m_ms); + static void thread_func(unsigned ms, event_handler * eh, std::timed_mutex * mutex) { + auto end = std::chrono::steady_clock::now() + std::chrono::milliseconds(ms); - while (!st->m_mutex.try_lock_until(end)) { - if (std::chrono::steady_clock::now() > end) { - st->m_eh->operator()(TIMEOUT_EH_CALLER); - return nullptr; - } + while (!mutex->try_lock_until(end)) { + if (std::chrono::steady_clock::now() >= end) { + eh->operator()(TIMEOUT_EH_CALLER); + return; + } } - st->m_mutex.unlock(); - return nullptr; + mutex->unlock(); } - imp(unsigned ms, event_handler * eh): - m_eh(eh), m_ms(ms) { +public: + imp(unsigned ms, event_handler * eh) { m_mutex.lock(); - m_thread = std::thread(thread_func, this); + m_thread = std::thread(thread_func, ms, eh, &m_mutex); } ~imp() { m_mutex.unlock(); - while (!m_thread.joinable()) { - std::this_thread::yield(); - } m_thread.join(); } - }; scoped_timer::scoped_timer(unsigned ms, event_handler * eh) { @@ -69,6 +63,5 @@ scoped_timer::scoped_timer(unsigned ms, event_handler * eh) { } scoped_timer::~scoped_timer() { - if (m_imp) - dealloc(m_imp); + dealloc(m_imp); }