Skip to content

Commit

Permalink
Merge pull request #1188 from zManu3k/master
Browse files Browse the repository at this point in the history
Fixed memory leak in threadpool
  • Loading branch information
COM8 authored Feb 24, 2025
2 parents 16c5e26 + c9f1fbe commit 12ac5f8
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 9 deletions.
9 changes: 4 additions & 5 deletions cpr/threadpool.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
#include <algorithm>
#include <chrono>
#include <cstddef>
#include <ctime>
#include <memory>
#include <mutex>
#include <thread>
Expand Down Expand Up @@ -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;
Expand All @@ -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<std::thread>([this] {
bool initialRun = true;
while (status != STOP) {
{
Expand Down Expand Up @@ -119,11 +118,11 @@ bool ThreadPool::CreateThread() {
return true;
}

void ThreadPool::AddThread(std::thread* thread) {
void ThreadPool::AddThread(const std::shared_ptr<std::thread>& thread) {
thread_mutex.lock();
++cur_thread_num;
ThreadData data;
data.thread = std::shared_ptr<std::thread>(thread);
data.thread = thread;
data.id = thread->get_id();
data.status = RUNNING;
data.start_time = std::chrono::steady_clock::now();
Expand Down
8 changes: 4 additions & 4 deletions include/cpr/threadpool.h
Original file line number Diff line number Diff line change
Expand Up @@ -53,19 +53,19 @@ class ThreadPool {
return idle_thread_num;
}

bool IsStarted() {
bool IsStarted() const {
return status != STOP;
}

bool IsStopped() {
bool IsStopped() const {
return status == STOP;
}

int Start(size_t start_threads = 0);
int Stop();
int Pause();
int Resume();
int Wait();
int Wait() const;

/**
* Return a future, calling future.get() will wait task done and return RetType.
Expand Down Expand Up @@ -95,7 +95,7 @@ class ThreadPool {

private:
bool CreateThread();
void AddThread(std::thread* thread);
void AddThread(const std::shared_ptr<std::thread>& thread);
void DelThread(std::thread::id id);

public:
Expand Down

0 comments on commit 12ac5f8

Please sign in to comment.