From c9f1fbe22d5031c5c1ecfcfac715c3cc192f345f Mon Sep 17 00:00:00 2001 From: zManu3k Date: Sun, 23 Feb 2025 20:06:13 +0100 Subject: [PATCH] Fixed memory leak in threadpool --- cpr/threadpool.cpp | 9 ++++----- include/cpr/threadpool.h | 8 ++++---- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/cpr/threadpool.cpp b/cpr/threadpool.cpp index 36b6400da..105c02039 100644 --- a/cpr/threadpool.cpp +++ b/cpr/threadpool.cpp @@ -2,7 +2,6 @@ #include #include #include -#include #include #include #include @@ -66,7 +65,7 @@ int ThreadPool::Resume() { return 0; } -int ThreadPool::Wait() { +int ThreadPool::Wait() const { while (true) { if (status == STOP || (tasks.empty() && idle_thread_num == cur_thread_num)) { break; @@ -80,7 +79,7 @@ bool ThreadPool::CreateThread() { if (cur_thread_num >= max_thread_num) { return false; } - std::thread* thread = new std::thread([this] { + auto thread = std::make_shared([this] { bool initialRun = true; while (status != STOP) { { @@ -119,11 +118,11 @@ bool ThreadPool::CreateThread() { return true; } -void ThreadPool::AddThread(std::thread* thread) { +void ThreadPool::AddThread(const std::shared_ptr& thread) { thread_mutex.lock(); ++cur_thread_num; ThreadData data; - data.thread = std::shared_ptr(thread); + data.thread = thread; data.id = thread->get_id(); data.status = RUNNING; data.start_time = std::chrono::steady_clock::now(); diff --git a/include/cpr/threadpool.h b/include/cpr/threadpool.h index ec402a422..346ff025c 100644 --- a/include/cpr/threadpool.h +++ b/include/cpr/threadpool.h @@ -53,11 +53,11 @@ class ThreadPool { return idle_thread_num; } - bool IsStarted() { + bool IsStarted() const { return status != STOP; } - bool IsStopped() { + bool IsStopped() const { return status == STOP; } @@ -65,7 +65,7 @@ class ThreadPool { int Stop(); int Pause(); int Resume(); - int Wait(); + int Wait() const; /** * Return a future, calling future.get() will wait task done and return RetType. @@ -95,7 +95,7 @@ class ThreadPool { private: bool CreateThread(); - void AddThread(std::thread* thread); + void AddThread(const std::shared_ptr& thread); void DelThread(std::thread::id id); public: