-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfixedThreadPool.cpp
More file actions
50 lines (44 loc) · 1.11 KB
/
fixedThreadPool.cpp
File metadata and controls
50 lines (44 loc) · 1.11 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
#include "fixedThreadPool.h"
#include <iostream>
namespace ThreadPools {
FixedThreadPool::FixedThreadPool(size_t numThreads) {
numThreads = std::max(numThreads, static_cast<size_t>(1));
for (size_t i = 0; i < numThreads; ++i) {
workers_.push(std::thread(&FixedThreadPool::worker_loop_, this));
}
}
FixedThreadPool::~FixedThreadPool() {
stop();
}
void FixedThreadPool::stop(bool wait) {
if (isTerminated_.load())
return;
ifWait_.store(wait);
isTerminated_.store(true);
task_cond_.notify_all();
std::thread t;
while (workers_.try_pop(t)) {
if(t.joinable())
t.join();
}
}
void FixedThreadPool::worker_loop_() {
Task task;
while (true) {
{
std::unique_lock<std::mutex> lock(taskMutex_);
task_cond_.wait(lock, [this] {return !tasks_.empty() || isTerminated_.load(); });
if (isTerminated_.load()) {
// 如果任务队列为空,则退出线程
// 如果任务不为空,并且不想等待,则退出线程
if (tasks_.empty() || !ifWait_.load()) {
return;
}
}
task = std::move(tasks_.back());
tasks_.pop_back();
}
task();
}
}
} // namespace ThreadPools