Q:
Q1:为什么vcpkg对于g++的支持这么差!
Q2:为什么vcpkg装g++的boost总是装不上!
Q3:为什么vcpkg装g++的protobuf也是装不上!用不了!
线程池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();
}
});
}
}
逐关键字解释
explicit ThreadPool(size_t num_threads = std::thread::hardware_concurrency()): stop(false)
explicit:
- 作用:防止隐式类型转换和防止拷贝初始化。
- 例如,ThreadPool pool = 4; 会编译错误,而必须写成 ThreadPool pool(4);。这可以避免一些意外的类型转换错误
std::thread::hardware_concurrency()
- 获取可以并发的核心数
- PS:可以改成任意的合法数字此种写法默认全部线程创建
stop(false)
- 初始化 stop 标志为 false,表示线程池刚开始运行时,所有线程都应该继续工作。
for (size_t i = 0; i < num_threads; ++i)
- 创建与可以并发的核心数一样的工作线程
workers.emplace_back()
- workers(为类里存放工作线程的集合)
- emplace_back()此方法为在可以接受构造对象所需的参数
- PS:对比push_back()方法,不接受传参构造,只存放构造完成的参数
this
- 匿名函数构造
- 作用:为每个创建的线程进行无限循环
std::function<void()> task;
- 嵌套于for循环
- 每次循环都创建一个新的 task 对象,循环结束时,task 被销毁,下次循环重新创建
- 作用:
- 1、实现每个线程的重复利用
- 2、将传入的任务打包成函数
std::unique_lockstd::mutex lock(this->queue_mutex);
- 为该线程加锁
