Ai
1 Star 0 Fork 0

Shawy/2023Linux

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
ThreadPool.hpp 2.03 KB
一键复制 编辑 原始数据 按行查看 历史
Shawy 提交于 2023-04-26 15:17 +08:00 . ThreadPool Test1
#pragma once
#include "LockGuard.hpp"
#include "Thread.hpp"
#include <vector>
#include <queue>
#include <unistd.h>
#define THREAD_NUM 5
template<class T>
class ThreadPool
{
public:
void waitCond()
{
pthread_cond_wait(&_cond, &_lock);
}
pthread_mutex_t* getMutex()
{
return &_lock;
}
T getTask()
{
T t = _task_queue.front();
_task_queue.pop();
return t;
}
bool empty()
{
return _task_queue.empty();
}
// 测试
void joins()
{
for(auto& it : _threads)
{
it->join();
}
}
public:
ThreadPool(int thread_num = THREAD_NUM)
: _num(thread_num)
{
pthread_mutex_init(&_lock, nullptr);
pthread_cond_init(&_cond, nullptr);
for(int i = 1; i <= _num; i++)
{
// 参数列表对应着Thread的构造函数
_threads.push_back(new Thread(i, routine, this));
}
}
~ThreadPool()
{
for(auto& it : _threads)
{
it->join();
delete it;
}
pthread_mutex_destroy(&_lock);
pthread_cond_destroy(&_cond);
}
// 线程执行任务
void run()
{
for(auto& it : _threads)
{
it->start();
std::cout << it->name() << "开始执行任务" << std::endl;
}
}
// 将任务入队列
void pushTask(const T& task)
{
LockGuard LockGuard(&_lock);
_task_queue.push(task);
pthread_cond_signal(&_cond);
}
// 线程函数
static void* routine(void* args)
{
ThreadData *td = (ThreadData*)args;
ThreadPool<T>* tp = (ThreadPool<T>*)td->_args;
while(1)
{
// sleep(1);
T task;
{
LockGuard LockGuard(tp->getMutex());
while(tp->empty())
{
tp->waitCond();
}
// 读取任务
task = tp->getTask(); // 任务[共享空间]->获取[私有空间]
}
std:: cout << "消费者" << td->_name;
task(); // 执行任务
}
// _task_queue.pop();
// while(1)
// {
// std::cout << td->_name << std::endl;
// sleep(1);
// }
}
private:
std::vector<Thread*> _threads; // 保存线程的数组
std::queue<T> _task_queue; // 保存任务的队列
int _num; // 线程的个数
pthread_mutex_t _lock; // 互斥锁
pthread_cond_t _cond; // 条件变量
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/shawyxy/2023-linux.git
git@gitee.com:shawyxy/2023-linux.git
shawyxy
2023-linux
2023Linux
main

搜索帮助