线程池
#include <iostream>
#include <thread>
#include <queue>
#include <vector>
#include <mutex>
#include <condition_variable>
using namespace std;
using callback = void(*)(void*);
/// @brief 任务类型
class Task{
public:
/// @brief 执行函数
callback func;
/// @brief 执行函数参数
void * args;
Task(callback f_, void* args_) {
func = f_;
args = args_;
}
};
/// @brief 线程池
class ThreadPool {
public:
ThreadPool(int threadNums_ = 10, int taskNums_ = 100) : isStop(false) {
for (int i = 0; i < threadNums_; i++) {
threads.push_back(new thread(worker, this));
}
taskNums = tasknums_;
}
~ThreadPool() {
isStop = true;
for (auto &th : threads) {
if (th.joinable()) {
th.join();
}
}
}
/// @brief 线程执行函数
/// @return
static void worker(void *args) {
ThreadPool* pool = static_cast<ThreadPool* >(args);
while(true) {
if (isStop) {
return;
}
unique_lock<mutex> lk(pool->mutexPool);
while(pool->tasks.empty() && pool->isStop == false) {
pool->cond.wait(lk)
}
Task t = pool->tasks.front();
pool->tasks.pop();
lk.unlock();
t->func(t->args);
}
}
bool addTask(Task t) {
if (tasks.size() == taskNums || isStop) {
return false;
}
{
unique_lock<mutex> lk(pool->mutexPool);
tasks.push(t);
cond.notify_all();
}
return true;
}
private:
/// @brief 终止信号
bool isStop;
/// @brief 线程数
int taskNums;
/// @brief 任务队列
queue<Task> tasks;
/// @brief 线程数组
vector<thread> threads;
/// @brief 线程池锁
mutex mutexPool;
/// @brief 条件变量
condition_variable cond;
};
资料:
https://blog.csdn.net/weixin_45144862/article/details/126914327
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通