Skip to content

Commit fd47865

Browse files
committed
Thread/ThreadPool: Fix deadlock
1 parent 392f607 commit fd47865

1 file changed

Lines changed: 10 additions & 7 deletions

File tree

modules/Thread/ThreadPool.mpp

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ export namespace CppUtils::Thread
3232

3333
inline ~ThreadPool()
3434
{
35+
m_stopRequested = true;
3536
for (auto& worker : m_workers)
3637
worker.requestStop();
3738
m_startWorkingCondition.notify_all();
@@ -79,21 +80,22 @@ export namespace CppUtils::Thread
7980

8081
inline auto workerThread() -> void
8182
{
82-
if (isTasksQueueEmpty())
83-
{
84-
auto tasksQueueAccessor = m_tasksQueue.access();
85-
m_startWorkingCondition.wait(tasksQueueAccessor.getLockGuard());
86-
}
87-
88-
m_activeWorkers.fetch_add(1, std::memory_order_relaxed);
8983
auto task = Task{};
84+
9085
{
9186
auto tasksQueueAccessor = m_tasksQueue.access();
87+
m_startWorkingCondition.wait(tasksQueueAccessor.getLockGuard(), [this, &tasksQueueAccessor] {
88+
return not std::empty(tasksQueueAccessor.value()) or m_stopRequested.load(std::memory_order_relaxed);
89+
});
90+
9291
if (std::empty(tasksQueueAccessor.value()))
9392
return;
93+
9494
task = std::move(tasksQueueAccessor->front());
9595
tasksQueueAccessor->pop();
9696
}
97+
98+
m_activeWorkers.fetch_add(1, std::memory_order_relaxed);
9799
try
98100
{
99101
task();
@@ -143,5 +145,6 @@ export namespace CppUtils::Thread
143145

144146
mutable std::shared_mutex m_onErrorMutex;
145147
std::function<void(std::exception_ptr)> m_onError;
148+
std::atomic<bool> m_stopRequested = false;
146149
};
147150
}

0 commit comments

Comments
 (0)