From 140902185fe915c135ab60dc89520cb2fb341ec9 Mon Sep 17 00:00:00 2001 From: Redacted Date: Sun, 13 Jul 2025 13:23:04 -0400 Subject: [PATCH] Update Thread.cpp Fixed a bug that caused a race between ~Thread and Thread::Runner receiving a new job from the threadpool --- include/MultiThreading/ThreadPool.h | 1 - src/Thread.cpp | 17 ++++++++++++----- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/include/MultiThreading/ThreadPool.h b/include/MultiThreading/ThreadPool.h index b11dd51..aaf8e28 100644 --- a/include/MultiThreading/ThreadPool.h +++ b/include/MultiThreading/ThreadPool.h @@ -49,6 +49,5 @@ public: /// Waits for the threads to empty the queue and destroys the thread pool. /// @note This should be one of the very last things your program does before exiting. - // TODO make Enqueue fail during destruction to avoid stalls. ~ThreadPool(); }; \ No newline at end of file diff --git a/src/Thread.cpp b/src/Thread.cpp index d30ff90..c9808ef 100644 --- a/src/Thread.cpp +++ b/src/Thread.cpp @@ -5,13 +5,19 @@ using namespace MultiThreading; Thread::~Thread() { - if (current_task) - current_task->WaitComplete(); - stop = true; + std::shared_ptr task; + { + std::lock_guard lock(mtx); + task = current_task; + } + + if (task) + task->WaitComplete(); + + stop = true; cv.notify_one(); Join(); - // Thread exits gracefully. } bool Thread::SetTask(std::shared_ptr task) { @@ -43,9 +49,10 @@ void Thread::Runner() { if (stop) break; + auto task = current_task; lock.unlock(); - current_task->Run(); + task->Run(); lock.lock();