From 46ebf13020d5f1dbbdf898c6ba162780fe919365 Mon Sep 17 00:00:00 2001 From: Abo-go Date: Fri, 1 Mar 2024 11:25:25 +0800 Subject: [PATCH 1/2] Avoid worker still wait after notify_all by put m_shutdown under the protect of mutex --- include/ThreadPool.h | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/include/ThreadPool.h b/include/ThreadPool.h index b7bf84d..b064ea6 100644 --- a/include/ThreadPool.h +++ b/include/ThreadPool.h @@ -24,9 +24,13 @@ class ThreadPool { void operator()() { std::function func; bool dequeued; - while (!m_pool->m_shutdown) { + while (true) { { std::unique_lock lock(m_pool->m_conditional_mutex); + if (m_pool->m_shutdown) + { + break; + } if (m_pool->m_queue.empty()) { m_pool->m_conditional_lock.wait(lock); } @@ -64,8 +68,11 @@ class ThreadPool { // Waits until threads finish their current task and shutdowns the pool void shutdown() { - m_shutdown = true; - m_conditional_lock.notify_all(); + { + std::unique_lock lock(m_conditional_mutex); + m_shutdown = true; + m_conditional_lock.notify_all(); + } for (int i = 0; i < m_threads.size(); ++i) { if(m_threads[i].joinable()) { From 0edeaf668983742d5deced839cfb0bcab6376290 Mon Sep 17 00:00:00 2001 From: Abo-go Date: Fri, 1 Mar 2024 11:35:46 +0800 Subject: [PATCH 2/2] Add SafeQueue Copy Construct --- include/SafeQueue.h | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/include/SafeQueue.h b/include/SafeQueue.h index 3c0ff74..954206a 100644 --- a/include/SafeQueue.h +++ b/include/SafeQueue.h @@ -15,7 +15,8 @@ class SafeQueue { } SafeQueue(SafeQueue& other) { - //TODO: + std::unique_lock lock(other.m_mutex); + m_queue = other.m_queue; } ~SafeQueue() { @@ -49,4 +50,4 @@ class SafeQueue { m_queue.pop(); return true; } -}; \ No newline at end of file +};