当前位置: 首页 > news >正文

Linux应用——线程池

1. 线程池要求

我们创建线程池的目的本质上是用空间换取时间,而我们选择于 C++ 的类内包装原生线程库的形式来创建,其具体实行逻辑如图

可以看到,整个线程池其实就是一个大型的 CP 模型,接下来我们来完成它

2. 整体模板

#pragma once#include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <pthread.h>struct ThreadInfo
{pthread_t tid;std::string name;
};static const int defalutnum = 5;template<class T>
class ThreadPool
{
public:ThreadPoo1(int num = defalutnum):threads_(num){pthread_mutex_init(&mutex_, nullptr);pthread_cond_init(&cond_, nullptr);}~ThreadPoo1(){pthread_mutex_destroy(&mutex_);pthread_mutex_destroy(&cond_);}
private:std::vector<ThreadInfo> threads_;std::queue<T>tasks_;pthread_mutex_t mutex_;pthread_cond_t cond_;
};

3. 具体实现

#pragma once#include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <pthread.h>// 存储线程池中各个线程信息
struct ThreadInfo
{pthread_t tid;std::string name;
};// 默认线程池容量
static const int defalutnum = 5;template<class T>
class ThreadPool
{
private:// 加锁void Lock(){pthread_mutex_lock(&mutex_);}// 释放锁void Unlock(){pthread_mutex_unlock (&mutex_);}// 唤醒线程void Wakeup(){pthread_cond_signal(&cond_);}// 资源不就绪, 线程同步void ThreadSleep(){pthread_cond_wait(&cond_, &mutex_);}// 对当前任务列表判空bool IsQueueEmpty(){return tasks_.size() == 0 ? true : false;}// 获取线程 namestd::string GetThreadName(pthread_t tid){for (const auto &ti : threads_){if (ti.tid == tid)return ti.name;}return "None";}
public:ThreadPool(int num = defalutnum):threads_(num){pthread_mutex_init(&mutex_, nullptr);pthread_cond_init(&cond_, nullptr);}// 由于 pthread_create 函数的特殊性// 只能将 HandlerTask 设置为静态函数// 同时将 this 指针以参数的形式传入static void *HandlerTask(void *args){ThreadPool<T> *tp = static_cast<ThreadPool<T> *>(args);while (true){// 确保同一时刻只有一个线程在进行消费tp->Lock();// 如果当前任务列表为空就让线程等待资源// 为防止伪唤醒的情况, 使用 whilewhile (tp->IsQueueEmpty()){tp->ThreadSleep();}T t = tp->Pop();tp->Unlock();// 执行任务// 注: 需要任务中重载 operator()t();}}// 启动线程池void Start(){int num = threads_.size();for (int i = 0; i < num; i++){threads_[i].name = "thread-" + std::to_string(i+1);pthread_create(&(threads_[i].tid), nullptr, HandlerTask, this);}}// Pop 函数在锁内执行因此不需要单独加锁T Pop(){T t = tasks_.front();tasks_.pop();return t;}// 将外界资源投入线程池void Push(const T &t){Lock();tasks_.push(t);Wakeup(); // 投入资源成功后唤醒线程 Unlock();}~ThreadPool(){pthread_mutex_destroy(&mutex_);pthread_cond_destroy(&cond_);}
private:std::vector<ThreadInfo> threads_; // 线程池中所有线程的信息std::queue<T> tasks_;             // 任务队列pthread_mutex_t mutex_;           // 互斥锁pthread_cond_t cond_;             // 条件变量
};

4. 使用测试

在这里我们引用一个 Task.hpp 的任务工具,如下

#pragma once#include "Log.hpp"
#include <iostream>
#include <string>std::string opers = "+-*/%";enum ErrorCode
{DevideZero,ModZero,Unknown,Normal
};class Task
{
public:Task(int x, int y, char op):a(x), b(y), op_(op) {}void operator()(){run();lg(Info, "run a task: %s", GetResult().c_str());}void run(){switch(op_){case '+':answer = a + b;break;case '-':answer = a - b;break;case '*':answer = a * b;break;case '/':if (b != 0) answer = a / b;else exitcode = DevideZero;break;case '%':if (b != 0) answer = a % b;else exitcode = ModZero;break;default:lg(Error, "Using correct operation: + - * / %");exitcode = Unknown;break;}}std::string GetTask(){std::string ret;ret += "Task: ";ret += std::to_string(a);ret += " ";ret += op_;ret += " ";ret += std::to_string(b);ret += " ";ret += "= ?";return ret;}std::string GetResult(){std::string ret;if (exitcode <= Unknown){ret += "run the task fail, reason: ";switch (exitcode){case DevideZero:ret += "DevideZero";break;case ModZero:ret += "ModZero";break;case Unknown:ret += "Unknown";break;default:break;}}else{ret += "run the task success, result: ";ret += std::to_string(a);ret += " ";ret += op_;ret += " ";ret += std::to_string(b);ret += " ";ret += "= ";ret += std::to_string(answer);}return ret;}~Task(){}private:int a;int b;char op_;int answer = 0;ErrorCode exitcode = Normal;
};

main 函数如下

#include <iostream>
#include <time.h>
#include "ThreadPool.hpp"
#include "Task.hpp"extern std::string opers;int main()
{ThreadPool<Task>* tp = new ThreadPool<Task>(5);tp->Start();srand(time(nullptr)^ getpid());while(true){//1.构建任务int x = rand() % 10 + 1;usleep(10);int y =rand() % 5;char op = opers[rand()%opers.size()];Task t(x, y, op);tp->Push(t);// 2.交给线程池处理lg(Info, "main thread make task: %s", t.GetTask().c_str());sleep(1);}return 0;
}

运行效果如下

也就是说我们想要使用这个线程池,只需要

1. 创建一个固定容量的进程池

2. 调用 Start() 函数启动进程池

3. 调用 Push() 函数向进程池中添加任务

即可! 

http://www.lryc.cn/news/481534.html

相关文章:

  • 95.【C语言】数据结构之双向链表的头插,头删,查找,中间插入,中间删除和销毁函数
  • leetcode82:删除排序链表中的重复节点||
  • 【C#】使用.net9在C#中向现有对象动态添加属性
  • Linux进程信号(信号的产生)
  • 97_api_intro_imagerecognition_pdf2word
  • 【算法】【优选算法】二分查找算法(上)
  • springboot初体验
  • 使用kalibr_calibration标定相机(realsense)和imu(h7min)
  • 绿色工厂认定流程
  • 《Python游戏编程入门》注-第5章5
  • LangChain Ollama实战文献检索助手(二)少样本提示FewShotPromptTemplate示例选择器
  • K倍区间 C++
  • Linux - 弯路系列3:安装和编译libvirt-4.5.0
  • Jenkins插件使用问题总结
  • u盘怎么重装电脑系统_u盘重装电脑系统步骤和详细教程【新手宝典】
  • Sql server查询数据库表的数量
  • Linux学习笔记之软件包管理RPM与YUM
  • 15分钟学 Go 第 41 天:中间件的使用
  • 《Python 与 SQLite:强大的数据库组合》
  • Golang | Leetcode Golang题解之第552题学生出勤记录II
  • Vue3 常用代码指南手抄,超详细 cheatsheet
  • 结构体是否包含特定类型的成员变量
  • 堆排序与链式二叉树:数据结构与排序算法的双重探索
  • 用 Python 从零开始创建神经网络(四):激活函数(Activation Functions)
  • 使用 Flask 和 ONLYOFFICE 实现文档在线编辑功能
  • 【C++】【算法基础】序列编辑距离
  • 【Android】轮播图——Banner
  • 学SQL,要安装什么软件?
  • webstorm 设置总结
  • 基于Spring Boot的养老保险管理系统的设计与实现,LW+源码+讲解