Note

std::thread 无拷贝构造函数,无法复制只能引用 &

Tip

<condition_variable> 里包含了 <mutex> 头文件。

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
#include <iostream>
#include <thread>
#include <condition_variable>
#include <queue>
#include <vector>
#include <functional>
#include <atomic>

class ThreadPool {
private:
std::mutex mtx;
std::condition_variable condition;
std::queue<std::function<void()>> tasks;
std::atomic<bool> stop;
std::vector<std::thread> threads;

public:
ThreadPool(int num_threads) : stop{ false } {
for (int i = 0; i < num_threads; i++) {
threads.emplace_back([this]() {
while (true)
{
std::unique_lock<std::mutex> lock(mtx);
condition.wait(lock, [this]() { return !tasks.empty() || stop; });
if (stop && tasks.empty()) return;
std::function<void()> task(std::move(tasks.front()));
tasks.pop();
lock.unlock();
task();
}
});
}
}
~ThreadPool() {
{
std::lock_guard<std::mutex> lock(mtx);
stop = true;
}
condition.notify_all();
for (auto& t : threads) {
t.join();
}
}
template<typename F, typename... Args> void enqueue(F&& f, Args&&... args) {
std::function<void()> task = std::bind(std::forward<F>(f), std::forward<Args>(args)...);
//auto task = [func = std::forward<F>(f), tup = std::make_tuple(std::forward<Args>(args)...)]() mutable { std::apply(std::move(func), std::move(tup)); }; C++17 引入 <tuple> 头文件 std::apply
//auto task = [func = std::forward<F>(f), ...args = std::forward<Args>((args)...)]() mutable { func = std::move((args)...); }; C++20 才支持包扩展用于初始化捕获 [...args = ...],用 lambda 替代 std::bind
if (stop) throw std::runtime_error("enqueue on stopped ThreadPool");
{
std::lock_guard<std::mutex> lock(mtx);
tasks.emplace(std::move(task));
//std::cout<< "task loaded" << "\n";
}
condition.notify_one();
}
};

int main() {
ThreadPool threadpool(6);
for (int i = 0; i < 500; i++) {
threadpool.enqueue([i]() {
std::cout << "task: " << i << " is running" << "\n";
std::this_thread::sleep_for(std::chrono::milliseconds(10));
std::cout << "task: " << i << " is done" << std::endl;
});
}

return 0;
}