-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadPool.h
More file actions
37 lines (28 loc) · 1.06 KB
/
ThreadPool.h
File metadata and controls
37 lines (28 loc) · 1.06 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
#pragma once
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
class ThreadPool {
public:
// 构造函数:初始化并启动给定数量的工作线程
explicit ThreadPool(size_t num_threads);
// 析构函数:负责优雅地关闭所有线程
~ThreadPool();
// 基础版的添加任务接口 (高级版带 future 和模板的我们留到下一步)
// 使用右值引用 && 和 std::move 来避免拷贝,实现零拷贝传递
void enqueue(std::function<void()>&& task);
private:
// 工作线程池:存储所有的线程对象
std::vector<std::thread> workers;
// 任务队列:存储所有待执行的任务
std::queue<std::function<void()>> tasks;
// 互斥锁:用于保护任务队列 tasks 的并发读写安全
std::mutex queue_mutex;
// 条件变量:用于阻塞和唤醒工作线程
std::condition_variable condition;
// 停止标志位:析构时置为 true,通知所有线程准备退出
bool stop;
};