-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreadpool.cpp
More file actions
84 lines (71 loc) · 2.08 KB
/
threadpool.cpp
File metadata and controls
84 lines (71 loc) · 2.08 KB
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
79
80
81
82
83
84
#include "threadpool.h"
#include <iostream>
namespace threadpool {
void Threadpool::init(int num) {
std::call_once(once_, [this, num]() {
writelock lock(mtx_);
hasStopped_.store(false);
isCancelled_.store(false);
workers_.reserve(num);
for (int i = 0; i < num; ++i) {
workers_.emplace_back(std::bind(&Threadpool::spawn, this));
}
isInitialized_.store(true);
});
}
void Threadpool::spawn() {
while (true) {
bool pop = false;
std::function<void()> task;
{
writelock lock(mtx_);
cond_.wait(lock, [this, &pop, &task] {
pop = tasks_.pop(task);
return isCancelled_.load() || hasStopped_.load() || pop;
});
}
if (isCancelled_.load() || (hasStopped_.load() && !pop)) {
return;
}
task();
}
}
void Threadpool::terminate() {
{
writelock lock(mtx_);
if (!isRunningImpl())
return;
hasStopped_.store(true);
}
cond_.notify_all();
for (auto &worker: workers_)
worker.join();
}
void Threadpool::cancel() {
{
writelock lock(mtx_);;
if (!isRunningImpl())
return;
isCancelled_.store(true);
}
tasks_.clear();
cond_.notify_all();
for (auto &worker: workers_)
worker.join();
}
bool Threadpool::isInitialized() const {
readlock lock(mtx_);
return isInitialized_.load();
}
bool Threadpool::isRunningImpl() const {
return isInitialized_.load() && !(hasStopped_.load()) && !(isCancelled_.load());
}
bool Threadpool::isRunning() const {
readlock lock(mtx_);
return isRunningImpl();
}
size_t Threadpool::size() const {
readlock lock(mtx_);
return workers_.size();
}
} // namespace threadpool