From 186c851695e77ce3c7f196b72cc4acd1c5573568 Mon Sep 17 00:00:00 2001 From: Mariusz Glebocki Date: Tue, 6 Jun 2023 01:40:36 +0200 Subject: [PATCH] Internals: Avoid pessimistic mutex locking in waitIfStopRequested() (#4272). No functional change intended. `stopRequested()` reads only atomic variables. It doesn't need a mutex to do this. This function is called in `waitIfStopRequested()`, which in turn is called before execution of every job, and inside some jobs. With this change the mutex inside `waitIfStopRequested` needs to be locked only in very rare cases instead of every time. --- src/V3ThreadPool.cpp | 6 +++--- src/V3ThreadPool.h | 9 ++------- 2 files changed, 5 insertions(+), 10 deletions(-) diff --git a/src/V3ThreadPool.cpp b/src/V3ThreadPool.cpp index 678270a13..63469681a 100644 --- a/src/V3ThreadPool.cpp +++ b/src/V3ThreadPool.cpp @@ -68,7 +68,7 @@ void V3ThreadPool::workerJobLoop(int id) VL_MT_SAFE { return !m_queue.empty() || m_shutdown || m_stopRequested; }); if (m_shutdown) return; // Terminate if requested - if (stopRequestedStandalone()) { continue; } + if (stopRequested()) { continue; } // Get the job UASSERT(!m_queue.empty(), "Job should be available"); @@ -115,9 +115,9 @@ void V3ThreadPool::requestExclusiveAccess(const V3ThreadPool::job_t&& exclusiveA } } -bool V3ThreadPool::waitIfStopRequested() VL_MT_SAFE { - V3LockGuard stoppedJobLock(m_stoppedJobsMutex); +bool V3ThreadPool::waitIfStopRequested() VL_MT_SAFE VL_EXCLUDES(m_stoppedJobsMutex) { if (!stopRequested()) return false; + V3LockGuard stoppedJobLock(m_stoppedJobsMutex); waitStopRequested(); return true; } diff --git a/src/V3ThreadPool.h b/src/V3ThreadPool.h index 3a97d7888..d87d5be17 100644 --- a/src/V3ThreadPool.h +++ b/src/V3ThreadPool.h @@ -93,7 +93,7 @@ public: // Check if other thread requested exclusive access to processing, // if so, it waits for it to complete. Afterwards it is resumed. // Returns true if request was send and we waited, otherwise false - bool waitIfStopRequested() VL_MT_SAFE; + bool waitIfStopRequested() VL_MT_SAFE VL_EXCLUDES(m_stoppedJobsMutex); // Waits for future. // This function can be interupted by exclusive access request. @@ -139,17 +139,12 @@ private: } // True when any thread requested exclusive access - bool stopRequested() const VL_REQUIRES(m_stoppedJobsMutex) { + bool stopRequested() const VL_MT_SAFE { // don't wait if shutdown already requested if (m_shutdown) return false; return m_stopRequested; } - bool stopRequestedStandalone() VL_MT_SAFE_EXCLUDES(m_stoppedJobsMutex) { - const V3LockGuard lock{m_stoppedJobsMutex}; - return stopRequested(); - } - // Waits until exclusive access job completes its job void waitStopRequested() VL_REQUIRES(m_stoppedJobsMutex);