-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadPool.cpp
More file actions
44 lines (35 loc) · 2.13 KB
/
ThreadPool.cpp
File metadata and controls
44 lines (35 loc) · 2.13 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
#include "ThreadPool.h"
// 构造函数:开张营业,招募指定数量的服务员(工作线程)
ThreadPool::ThreadPool(size_t num_threads) : stop(false) {
for (size_t i = 0; i < num_threads; ++i) {
// 使用 emplace_back 直接在 vector 尾部构造线程,避免拷贝
// 传入一个 Lambda 表达式 [this]{...} 作为线程要执行的函数
workers.emplace_back([this] {
// 这是每个服务员的“死循环”日常
while (true) {
std::function<void()> task;
{
// [填空 1]:给共享的任务队列上锁。
// 提示:使用 std::unique_lock<std::mutex> 绑定 queue_mutex
// [填空 2]:让服务员去睡觉,直到被铃铛唤醒。
// 提示:使用 condition.wait(lock, 谓词Lambda);
// 谓词Lambda []{ return ...; } 的逻辑是:
// 什么时候服务员应该醒来干活?(餐厅关门了 stop == true,或者 队列里有任务了 !tasks.empty())
// [填空 3]:醒来后,判断一下。如果餐厅要求关门了 (stop) 且 任务都做完了 (tasks.empty()),就退出死循环 (return)。
// [填空 4]:从 tasks 队列取出最前面的任务 (front),然后将其弹出队列 (pop)。
// 提示:为了零拷贝,可以使用 std::move(tasks.front()) 赋值给 task
} // 离开这个作用域,大括号会自动帮我们释放锁!这就是 RAII!
// [填空 5]:执行刚才取出的任务 (直接调用 task())
}
});
}
}
// 析构函数:餐厅关门,优雅地遣散服务员
ThreadPool::~ThreadPool() {
{
// [填空 6]:上锁,然后把 stop 标志位改成 true
}
// [填空 7]:按响厨房的铃铛,叫醒所有正在睡觉的服务员
// 提示:使用 condition.notify_all()
// [填空 8]:遍历 workers 数组,依次调用每个线程的 join() 方法,等待他们把手头的活儿干完再下班
}