实现简单的固定线程数的线程池

文章目录
  1. 1. 参考资料
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
作者:Graphene
链接:https://www.zhihu.com/question/27908489/answer/355105668
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

#include <mutex>
#include <condition_variable>
#include <functional>
#include <queue>
#include <thread>

class fixed_thread_pool {
public:
explicit fixed_thread_pool(size_t thread_count)
: data_(std::make_shared<data>()) {
for (size_t i = 0; i < thread_count; ++i) {
std::thread([data = data_] {
std::unique_lock<std::mutex> lk(data->mtx_);
for (;;) {
if (!data->tasks_.empty()) {
auto current = std::move(data->tasks_.front());
data->tasks_.pop();
lk.unlock();
current();
lk.lock();
} else if (data->is_shutdown_) {
break;
} else {
data->cond_.wait(lk);
}
}
}).detach();
}
}

fixed_thread_pool() = default;
fixed_thread_pool(fixed_thread_pool&&) = default;

~fixed_thread_pool() {
if ((bool) data_) {
{
std::lock_guard<std::mutex> lk(data_->mtx_);
data_->is_shutdown_ = true;
}
data_->cond_.notify_all();
}
}

template <class F>
void execute(F&& task) {
{
std::lock_guard<std::mutex> lk(data_->mtx_);
data_->tasks_.emplace(std::forward<F>(task));
}
data_->cond_.notify_one();
}

private:
struct data {
std::mutex mtx_;
std::condition_variable cond_;
bool is_shutdown_ = false;
std::queue<std::function<void()>> tasks_;
};
std::shared_ptr<data> data_;
};

非常僵硬的看不懂了,之后再来回味。。。。

参考资料