Skip to content

Commit 12ac5f8

Browse files
authored
Merge pull request #1188 from zManu3k/master
Fixed memory leak in threadpool
2 parents 16c5e26 + c9f1fbe commit 12ac5f8

File tree

2 files changed

+8
-9
lines changed

2 files changed

+8
-9
lines changed

cpr/threadpool.cpp

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
#include <algorithm>
33
#include <chrono>
44
#include <cstddef>
5-
#include <ctime>
65
#include <memory>
76
#include <mutex>
87
#include <thread>
@@ -66,7 +65,7 @@ int ThreadPool::Resume() {
6665
return 0;
6766
}
6867

69-
int ThreadPool::Wait() {
68+
int ThreadPool::Wait() const {
7069
while (true) {
7170
if (status == STOP || (tasks.empty() && idle_thread_num == cur_thread_num)) {
7271
break;
@@ -80,7 +79,7 @@ bool ThreadPool::CreateThread() {
8079
if (cur_thread_num >= max_thread_num) {
8180
return false;
8281
}
83-
std::thread* thread = new std::thread([this] {
82+
auto thread = std::make_shared<std::thread>([this] {
8483
bool initialRun = true;
8584
while (status != STOP) {
8685
{
@@ -119,11 +118,11 @@ bool ThreadPool::CreateThread() {
119118
return true;
120119
}
121120

122-
void ThreadPool::AddThread(std::thread* thread) {
121+
void ThreadPool::AddThread(const std::shared_ptr<std::thread>& thread) {
123122
thread_mutex.lock();
124123
++cur_thread_num;
125124
ThreadData data;
126-
data.thread = std::shared_ptr<std::thread>(thread);
125+
data.thread = thread;
127126
data.id = thread->get_id();
128127
data.status = RUNNING;
129128
data.start_time = std::chrono::steady_clock::now();

include/cpr/threadpool.h

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -53,19 +53,19 @@ class ThreadPool {
5353
return idle_thread_num;
5454
}
5555

56-
bool IsStarted() {
56+
bool IsStarted() const {
5757
return status != STOP;
5858
}
5959

60-
bool IsStopped() {
60+
bool IsStopped() const {
6161
return status == STOP;
6262
}
6363

6464
int Start(size_t start_threads = 0);
6565
int Stop();
6666
int Pause();
6767
int Resume();
68-
int Wait();
68+
int Wait() const;
6969

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

9696
private:
9797
bool CreateThread();
98-
void AddThread(std::thread* thread);
98+
void AddThread(const std::shared_ptr<std::thread>& thread);
9999
void DelThread(std::thread::id id);
100100

101101
public:

0 commit comments

Comments
 (0)