Skip to content

Commit ae5cd03

Browse files
author
Oscar Franco
committed
Add a waitFinished method to thread pool
1 parent 338a8da commit ae5cd03

2 files changed

Lines changed: 16 additions & 9 deletions

File tree

cpp/ThreadPool.cpp

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,13 @@ void ThreadPool::doWork()
8585
task = workQueue.front();
8686
workQueue.pop();
8787
}
88-
88+
++busy;
8989
task();
90+
--busy;
9091
}
9192
}
93+
94+
void ThreadPool::waitFinished() {
95+
std::unique_lock<std::mutex> g(workQueueMutex);
96+
workQueueConditionVariable.wait(g, [&]{ return workQueue.empty() && (busy == 0); });
97+
}

cpp/ThreadPool.h

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,22 +8,23 @@
88
#ifndef ThreadPool_hpp
99
#define ThreadPool_hpp
1010

11-
#include <stdio.h>
12-
#include <thread>
13-
#include <mutex>
1411
#include <condition_variable>
1512
#include <exception>
16-
#include <vector>
13+
#include <mutex>
1714
#include <queue>
15+
#include <stdio.h>
16+
#include <thread>
17+
#include <vector>
1818

19-
class ThreadPool
20-
{
19+
class ThreadPool {
2120
public:
2221
ThreadPool();
2322
~ThreadPool();
2423
void queueWork(std::function<void(void)> task);
25-
24+
void waitFinished();
25+
2626
private:
27+
unsigned int busy;
2728
// This condition variable is used for the threads to wait until there is work
2829
// to do
2930
std::condition_variable_any workQueueConditionVariable;
@@ -40,7 +41,7 @@ class ThreadPool
4041
// This will be set to true when the thread pool is shutting down. This tells
4142
// the threads to stop looping and finish
4243
bool done;
43-
44+
4445
// Function used by the threads to grab work from the queue
4546
void doWork();
4647
};

0 commit comments

Comments
 (0)