线程池类新1续1
enques函数2
源代码
template <typename F, typename... Arg>
auto ThreadPool::enques(F &&f, Arg &&...arg)
-> std::future<typename std::result_of<F(Arg...)>::type>
{
using functype = typename std::resulit_of<F(Arg..)>::type;
auto task = std::make_shared<std::packaged_task<functype>>(
std::bind(std::forward<F>(f), std::forward<Arg>(arg)...));
std::future<functype> retfuture = task->get_future();
{
std::lock_guard<std::mutx> lock_guard(this->mtx);
if (stop)
throw std::runtime_error("error:threadpool on off");
work_que.emplace([this](){
(*task)();
});
}
cv.notify_one();
return retfuture;
}
解释
using functype = typename std::resulit_of<F(Arg..)>::type;
- 将std::resulit_of<F(Arg..)>::type推导出的类型命名为functype
std::result_of<F(Arg…)>
- 用于在编译期推导可调用对象 F 接受参数 Arg… 后的返回类型
- Arg可能会有不定参数使用…去表示
- c++17开始被弃用,使用std::invoke_result_t
::type
- 是std::result_of的内部静态函数
- 是 std::result_of 内部定义的类型别名,表示推导出的返回类型
auto task = std::make_shared<std::packaged_task>(std::bind(std::forward(f), std::forward(arg)…))
- 创建一个完美转发的异步任务
auto task = std::make_shared<std::packaged_task>()
- auto task 自动推导类型为 shared_ptr<packaged_task>(并为其赋值创建的任务)
- std::make_shared<…>()是在在堆上创建对象,并返回 std::shared_ptr 智能指针,共享智能指针管理
- std::packaged_task是打包封装成一个异步任务
std::bind(std::forward(f), std::forward(arg)…)
这句代码是 C++ 中完美转发 + 函数绑定的组合,用于创建一个绑定好参数的可调用对象。
std::bind 将函数和参数绑定在一起,生成一个新的可调用对象。可以绑定部分参数(占位符)或全部参数 5#### using functype = typename std::resulit_of<F(Arg..)>::type;
将std::resulit_of<F(Arg..)>::type推导出的类型命名为functype
std::forward(f) 完美转发左右值(这里指函数名)
std::forward(arg)… 完美转发参数包中的每个参数以及其类别(这里指参数)
std::future retfuture = task->get_future();
- 从某个异步任务对象中获取一个 std::future 对象,并将其赋值给 retfuture。之后可以通过 retfuture.get() 来等待任务完成并获取其返回值。
std::future
- 声明一个 std::future 对象,模板参数 functype 是异步任务返回值的类型。
std::future
- 用于获取异步操作的结果。
retfuture
- 用于存储获取到的 future 对象。
task->get_future()
- 调用 task 指针所指向对象的 get_future() 成员函数。会返回一个与任务关联的 std::future 对象
std::lock_guardstd::mutx lock_guard(this->mtx);
- 创建一个 std::lock_guard 对象,在构造时自动锁定 this->mtx 互斥量,在析构时(离开作用域时)自动解锁。
- 保护对共享数据的访问
std::lock_guardstd::mutex
- std::lock_guard 是一个 RAII(资源获取即初始化)锁管理器。
- 这里用来管理线程锁
if (stop) throw std::runtime_error(“error:threadpool on off”);
- 判断线程池是否停止
- 是:进入抛出异常
work_que.emplace(this{(*task)();});
- 加入到线程池队列(通过对task名称解引用的方式获得函数就加入队列)
cv.notify_one();
- 唤醒一个线程去运行
return retfuture;
- 获取调用的结果
worker
源代码
void ThreadPool::worker() // 每个线程执行函数
{
while (1) // 死循环
{
std::function<void()> task; // 定义一临时存储异步任务的变量
{
std::unique_lock<std::mutex> lock(mtx); // 给mtx上锁
cv.wait(lock, [this]
{ return this->stop || !this->work_que.empty(); }); // 等待条件(是否是stop变量为false,或者任务队列是否为空)
if (stop && work_que.empty()) // stop==1并且任务队列为空,则关闭线程
return;
task = std::move(this->work_que.front()); // 给队列上面的赋值给task
this->work_que.pop(); // 出队
}
task(); // 执行task
}
}
解释
while (1)
- 死循环,使每个工作线程持续不断地从任务队列中获取任务并执行
- 线程不会主动退出,除非满足退出条件
std::function<void()> task;
- 定义一个可调用对象 task,用于临时存储从任务队列中取出的任务
- std::function<void()> 可以包装任何可调用目标(函数、lambda、bind表达式等),且返回类型为 void,无参数
std::unique_lockstd::mutex lock(mtx);
- 创建一个 std::unique_lock 对象,在构造时锁定互斥量 mtx
- 与 std::lock_guard 不同,std::unique_lock 更灵活,允许手动解锁/重新锁定,配合条件变量使用
std::unique_lockstd::mutex
- 是一个互斥量包装器,提供 RAII 风格的锁管理
- 支持延迟锁定、尝试锁定、定时锁定以及转移所有权等操作
- 条件变量 cv.wait() 要求参数必须是 std::unique_lock
cv.wait(lock, [this]{ return this->stop || !this->work_que.empty(); });
- 条件变量等待,线程在此处阻塞,直到条件满足(谓词返回 true)才被唤醒
- 等待期间自动解锁 lock,唤醒后重新锁定 lock
cv.wait(lock, predicate)
- 等价于
while (!predicate()) { cv.wait(lock); } - 避免虚假唤醒(spurious wakeup)
- predicate 是一个可调用对象,返回 bool 值
谓词 [this]{ return this->stop || !this->work_que.empty(); }
- 捕获 this 指针的 lambda 表达式
- 条件:线程池已停止(stop == true)或 任务队列不为空(!work_que.empty())
- 只要满足任一条件,线程就被唤醒继续执行
if (stop && work_que.empty()) return;
- 检查退出条件:线程池已停止 且 任务队列为空
- 两个条件同时满足时,线程安全退出,结束 while 死循环
- 如果只有 stop 为 true 但队列中还有未处理的任务,则继续处理完所有任务再退出
task = std::move(this->work_que.front());
- 将任务队列 front 处的任务通过 std::move 转移给 task 变量
- std::move 将左值转换为右值引用,避免拷贝,提高性能
std::move
- 将对象资源的所有权转移给另一个对象
- 转移后原对象处于有效但未指定的状态
this->work_que.pop();
- 将任务队列 front 处的元素弹出(出队)
- 与上一步配合:先取出任务,再将其从队列中移除
task();
- 执行取出的任务
- 调用 task 所包装的可调用对象,实际执行用户提交的函数
- 注意:此操作在锁的作用域之外执行,避免长时间持有锁影响其他线程
