Tip

std::thread::hardware_concurrency() 返回 CPU 线程数,可作为线程池默认大小。

时间计数代码

1
2
3
4
5
6
//时间计数 us微秒 = micro 
auto t0 = std::chrono::steady_clock::now();
//代码
auto ms = std::chrono::duration<double, std::milli>(
std::chrono::steady_clock::now() - t0).count();
std::cout << "全部任务耗时 " << ms << " ms\n";

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

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;

ThreadPool(const ThreadPool&) = delete;
ThreadPool& operator=(const ThreadPool&) = delete;
ThreadPool(int num_threads);

public:
static ThreadPool& SetThreadPool(int num_threads) {
static ThreadPool threadpool(num_threads);
return threadpool;
}

~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)...);
if (stop) throw std::runtime_error("enqueue on stopped ThreadPool");
{
std::lock_guard<std::mutex> lock(mtx);
tasks.emplace(std::move(task));
}
condition.notify_one();
}
};

ThreadPool::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();
}
});
}
}

int main() {
ThreadPool& threadpool = ThreadPool::SetThreadPool(std::thread::hardware_concurrency());
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;
}