-
Notifications
You must be signed in to change notification settings - Fork 0
/
threadpool.cpp
47 lines (41 loc) · 1.22 KB
/
threadpool.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <vector>
#include <functional>
#include "threadpool.h"
// Create a thread pool with the specidied number of threads
ThreadPool::ThreadPool(int threadCount)
{
Threads.reserve(threadCount);
for (int i = 0; i < threadCount; ++i)
{
Threads.push_back(std::thread([this](){
while (true)
{
std::function<void(void)> work;
{
std::unique_lock<std::mutex> queueGuard{QueueLock};
QueueNotEmptyCondition.wait(queueGuard, [this](){return !Queue.empty();});
work = Queue.front();
Queue.pop();
}
if (work == nullptr) break;
else work();
}
}));
}
}
// Terminate all threads in the pool after all outstanding work items have been processed
ThreadPool::~ThreadPool()
{
{
std::lock_guard<std::mutex> queueGuard{QueueLock};
for (std::thread& thread : Threads)
Queue.push(nullptr);
}
QueueNotEmptyCondition.notify_all();
for (std::thread& thread : Threads)
thread.join();
}