线程池续1
类的构造函数源码使用:
explicit ThreadPool(size_t num_threads = std::thread::hardware_concurrency()): stop(false) {
for (size_t i = 0; i < num_threads; ++i) {
workers.emplace_back([this] {
// 每个工作线程的无限循环
for (;;) {
std::function<void()> task;
{
// 加锁获取任务
std::unique_lock<std::mutex> lock(this->queue_mutex);
// 等待条件:停止标志 或 任务队列非空
this->condition.wait(lock, [this] {
return this->stop || !this->tasks.empty();
});
// 如果停止且没有任务,退出线程
if (this->stop && this->tasks.empty())
return;
// 取出一个任务
task = std::move(this->tasks.front());
this->tasks.pop();
}
// 执行任务(在锁外执行,避免阻塞其他线程)
task();
}
});
}
}
逐关键字解释
- 是一个将下面的循环代码独立成代码块,用于控制std::unique_lock的生命周期
- 目的是尽早释放互斥锁,让其他线程能访问队列
this->condition.wait(lock, [this] {return this->stop || !this->tasks.empty();});
- condition.wait(lock, predicate)是等待predicate条件成立
- 自动释放锁,让其他线程能访问共享数据
- 线程休眠,不浪费 CPU
- 被通知后重新获取锁,再次检查条件
- 确保线程只在确实有工作要做时才被唤醒
线程池新1
源代码
ThreadPool::ThreadPool(size_t num_threads):stop(0)
{
for(size_t i=0;i<num_threads;i++)
{
workers.emplace_back([this]
{
this->worker();
});
}
}
解释
workers.emplace_back([this]{this->worker();});
- 类比一的只不过将内部的匿名函数抽象成worker
- 更便于理解
放入队列的源代码
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_all();
return retfuture;
}
逐行解释
template <typename F, typename… Arg>
- F为单个固定的模版参数,Arg为不固定数量的模版类型
auto ThreadPool::enques(F &&f, Arg &&…arg)
- 自动类型,这里的类型通过后面的[’->’]确认类型
- 强制需传入至少1个参数,Arg为不定参数’
std::future<typename std::result_of<F(Arg…)>::type>
- 为前面的类型
std::future
- 定义返回的异步的操作的结果
typename
- 任意变量类型
- 这是最常见的用法,告诉编译器后面的名字是一个类型,而不是静态成员变量或其他东西。
