Ai
1 Star 0 Fork 0

张耀铎/Linux初学者

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
ThreadPool_V2.hpp 2.77 KB
一键复制 编辑 原始数据 按行查看 历史
kongqizyd 提交于 2023-08-31 12:13 +08:00 . 2023.8.31 线程池
#pragma once
#include <iostream>
#include <memory>//智能指针的头文件
#include <string>
#include <vector>
#include <queue>
#include <unistd.h>
#include "Thread.hpp"
#include "task.hpp"
const static int N = 5;
template<class T>
class ThreadPool
{
public:
ThreadPool(int num = N):_num(num), _threads(num)//也可以不初始化_threads,因为我们用的是库,直接push就行
{
pthread_mutex_init(&_lock, nullptr);
pthread_cond_init(&_cond, nullptr);
}
void LockQueue() {pthread_mutex_lock(&_lock); }
void UnlockQueue() {pthread_mutex_unlock(&_lock); }
void ThreadWait() {pthread_cond_wait(&_cond, &_lock);
void ThreadWakeup() {pthread_cond_signal(&_cond); }
bool isEmpty() {return _tasks.empty(); }
T popTask()
{
T t = _tasks.front();
_tasks.pop();
return t;
}
static void threadRoutine(coid* args)//加static?类内的线程函数,要记得加static,放在静态区,因为在类内会有this指针,导致函数参数类型不对
{
pthread_deatach(pthread_self());
ThreadPool<T>* tp = static_cast<ThreadPool<T>*>(args);
while(true)
{
//1、检测有没有任务,有就处理,无就等待,这里一定要加锁
tp->LockQueue();
//因为是静态函数,不能直接访问类内私有成员,所以create函数那里要传this指针就可以了
if(tp->isEmpty())
{
tp->threadWait();
}
T t = tp->popTask()//从公共区域拿到私有区域
tp->UnlockQueue();
//测试
t();
std::cout << "thread handler done, result: " <<t.formatRes() << std::endl;
//t.run();//处理任务
}
}
void init()
{
//插入若干个线程
for(int i = 0; i < _num; i++)
{
_threads.push_back(Thread(i, threadRoutine, this));
}
}
void start()
{
for(auto& t: _threads)
{
t.run();
}
}
void check()
{
for(auto& t: _threads)
{
std::cout << t.threadname() << "running..." << std::endl;
}
}
void pushTask(const T& t)
{
LockQueue();
_task.push(t);
ThreadWait();
UnlockQueue();
}
~ThreadPool()
{
for(auto& t: _threads)
{
t.join();
}
pthread_mutex_destroy(&_lock);
pthread_cond_destroy(&_cond);
}
private:
std::vector<Thread> _threads;//pthread_t是用库中的
int _num;
std::queue<T> _tasks;//使用STL的自动扩容
pthread_mutex_t _lock;
pthread_cond_t _cond;//当没有任务,所有线程应当休息,挂起,所以用条件变量来控制
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C/C++
1
https://gitee.com/kongqizyd/linux-beginner.git
git@gitee.com:kongqizyd/linux-beginner.git
kongqizyd
linux-beginner
Linux初学者
master

搜索帮助