代码拉取完成,页面将自动刷新
#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; // 条件变量
};
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。