C++11 加入了线程库,从此告别了标准库不支持并发的历史。然而 c++ 对于多线程的支持还是比较低级,稍微高级一点的用法都需要自己去实现,譬如线程池、信号量等。线程池(thread pool)这个东西,在面试上多次被问到,一般的回答都是:“管理一个任务队列,一个线程队列,然后每次取一个任务分配给一个线程去做,循环往复。” 貌似没有问题吧。但是写起程序来的时候就出问题了。
下面给出线程池的代码 threadpool.h
#pragma once
#ifndef THREAD_POOL_H
#define THREAD_POOL_H
#include
#include
#include
#include
#include
using namespace std;
class threadpool
{
private:
using Task = function; //定义线程类型
vector _pool; //线程池
queue _tasks; //任务队列
mutex _lock; //同步
condition_variable _task_cv; //条件阻塞
atomic _run{ true }; //线程池是否执行
atomic _idlThrNum{ 0 }; //空闲线程数量
public:
inline threadpool(unsigned short size = 4) { addThread(size); }
inline ~threadpool()
{
_run=false;
_task_cv.notify_all(); // 唤醒所有线程执行
for (thread& thread : _pool)
{
if (thread.joinable())
{
thread.join(); // 等待任务结束, 前提:线程一定会执行完
}
}
}
public:
// 提交一个任务,调用.get()获取返回值会等待任务执行完,获取返回值
template
auto commit(F&& f, Args&&... args) ->future
{
if (!_run)
throw runtime_error("commit on ThreadPool is stopped.");
using RetType = decltype(f(args...));
auto task = make_shared(
bind(forward(f), forward(args)...)
);
future future = task->get_future();
{
// 添加任务到队列
lock_guard lock{ _lock };
_tasks.emplace([task](){
(*task)();
});
}
_task_cv.notify_one(); // 唤醒一个线程执行
return future;
}
//空闲线程数量
int idlCount() { return _idlThrNum; }
//线程数量
int thrCount() { return _pool.size(); }
private:
//添加指定数量的线程
void addThread(unsigned short size)
{
//获取硬件可支持的并发线程数量
const int thread_max_counts = std::thread::hardware_concurrency();
for (; _pool.size() 0; --size)
{
//增加线程数量,但不超过 预定义数量 thread_max_counts
_pool.emplace_back( [this]{ //工作线程函数
while (_run)
{
Task task; // 获取一个待执行的 task
{
unique_lock lock{ _lock };
// wait 直到有 task
_task_cv.wait(lock, [this]{
return !_run || !_tasks.empty();
});
if (!_run && _tasks.empty())
return;
task = move(_tasks.front()); // 按先进先出从队列取一个 task
_tasks.pop();
}
_idlThrNum--;
task(); //执行任务
_idlThrNum++;
}
});
_idlThrNum++;
}
}
};
#endif
该线程池的实现全部是在头文件做的,不需要cpp文件
main函数测试代码
#include "threadpool.h"
#include
#include
using namespace std;
//普通函数
void fun1(int slp)
{
cout
关注
打赏
最近更新
- 深拷贝和浅拷贝的区别(重点)
- 【Vue】走进Vue框架世界
- 【云服务器】项目部署—搭建网站—vue电商后台管理系统
- 【React介绍】 一文带你深入React
- 【React】React组件实例的三大属性之state,props,refs(你学废了吗)
- 【脚手架VueCLI】从零开始,创建一个VUE项目
- 【React】深入理解React组件生命周期----图文详解(含代码)
- 【React】DOM的Diffing算法是什么?以及DOM中key的作用----经典面试题
- 【React】1_使用React脚手架创建项目步骤--------详解(含项目结构说明)
- 【React】2_如何使用react脚手架写一个简单的页面?