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