-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy paththread_pool.cc
78 lines (67 loc) · 1.68 KB
/
thread_pool.cc
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include "thread_pool.h"
#include <cassert>
#include <functional>
#include "spdlog/spdlog.h"
namespace tl {
ThreadPool::ThreadPool(size_t num_threads, int priority_count) : stop_(false) {
assert(priority_count > 0);
for (size_t i = 0; i < num_threads; i++) {
threads_.emplace_back([this] { this->loop(); });
}
tasks_.reserve(priority_count);
for (int i = 0; i < priority_count; i++) {
tasks_.push_back(std::queue<std::function<void()>>());
}
}
ThreadPool::~ThreadPool() {
{
std::unique_lock<std::mutex> lock(tasks_mutex_);
stop_ = true;
}
condition_.notify_all();
for (auto& t : threads_) t.join();
}
void ThreadPool::loop() {
for (;;) {
bool got_task = false;
std::function<void()> task;
{
// wait for new task or stop signal
std::unique_lock<std::mutex> lock(tasks_mutex_);
condition_.wait(lock, [this] {
bool allempty = true;
for (auto tp : this->tasks_) {
if (!tp.empty()) {
allempty = false;
break;
}
}
return this->stop_ || !allempty;
});
// exit loop when stop and no more tasks
bool allempty = true;
for (auto tp : this->tasks_) {
if (!tp.empty()) {
allempty = false;
break;
}
}
if (stop_ && allempty) return;
for (auto& task_list : tasks_) {
if (task_list.empty()) {
continue;
}
task = std::move(task_list.front());
task_list.pop();
got_task = true;
break;
}
}
if (got_task) task();
}
}
bool ThreadPool::stop() {
std::unique_lock<std::mutex> lock(tasks_mutex_);
return stop_;
}
} // namespace tl