-
Notifications
You must be signed in to change notification settings - Fork 0
/
ThreadPool.cpp
50 lines (42 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
48
49
50
#include "ThreadPool.h"
ThreadPool::ThreadPool(size_t numThreads) : stop(false), tasksCompleted(0) {
for (size_t i = 0; i < numThreads; ++i) {
workers.emplace_back([this]() { this->workerThread(); });
}
}
ThreadPool::~ThreadPool() {
{
unique_lock<mutex> lock(queueMutex);
stop = true;
}
condition.notify_all();
for (auto& worker : workers) {
worker.join();
}
}
void ThreadPool::addTask(const function<void()>& task) {
unique_lock<mutex> lock(queueMutex);
tasks.push(task);
condition.notify_one();
}
void ThreadPool::waitForAllTasks() {
unique_lock<mutex> lock(queueMutex);
condition.wait(lock, [this]() { return tasks.empty() && tasksCompleted == workers.size(); });
}
void ThreadPool::workerThread() {
while (true) {
function<void()> task;
{
unique_lock<mutex> lock(queueMutex);
condition.wait(lock, [this]() { return stop || !tasks.empty(); });
if (stop && tasks.empty()) {
condition.notify_all();
return;
}
task = move(tasks.front());
tasks.pop();
}
task();
++tasksCompleted; // 已经完成任务的数量
}
}