代码拉取完成,页面将自动刷新
#pragma once
#include<iostream>
#include<queue>
#include<pthread.h>
#include<mutex>
#include"Task.hpp"
#include"Protocol.hpp"
#include"log.hpp"
using namespace std;
#define NUM 6
class ThreadPool
{
private:
ThreadPool(int num = NUM)
:_num(num),_stop(false)
{
pthread_mutex_init(&_mtx,nullptr);
pthread_cond_init(&_cond,nullptr);
}
ThreadPool(const ThreadPool& tp) = delete;
public:
static ThreadPool* GetInstance()
{
static pthread_mutex_t sigle_mutex = PTHREAD_MUTEX_INITIALIZER;
if(_sigleton==nullptr)
{
pthread_mutex_lock(&sigle_mutex);
if(_sigleton==nullptr)
{
_sigleton = new ThreadPool();
_sigleton->InitThreadPool();
}
pthread_mutex_unlock(&sigle_mutex);
}
return _sigleton;
}
~ThreadPool()
{
pthread_mutex_destroy(&_mtx);
pthread_cond_destroy(&_cond);
}
bool InitThreadPool()
{
for(int i = 0;i<_num;i++)
{
pthread_t tid;
if(pthread_create(&tid,nullptr,Routine, this)!=0)
{
logMessage(FATAL,"线程池启动失败: pthread_create error");
return false;
}
}
logMessage(DEBUG,"线程池创建成功");
return true;
}
void PushTask(const Task& task)
{
Lock();
_task_queue.push(task);
UnLock();
WakeUp();
}
void PopTask(Task& task)
{
//走到这儿一定能够拿到任务
task = _task_queue.front();
_task_queue.pop();
}
static void* Routine(void* args)
{
ThreadPool* tp = (ThreadPool*)args;
while(1)
{
//拿到任务区执行
Task t;
tp->Lock();
while(tp->TaskQueueIsEmpty())
{
tp->Wait();//醒来时一定是占有互斥锁的
}
tp->PopTask(t);
tp->UnLock();
t.ProcessOn();
}
}
void Wait()
{
pthread_cond_wait(&_cond,&_mtx);
}
void WakeUp()
{
pthread_cond_signal(&_cond);
}
void Lock()
{
pthread_mutex_lock(&_mtx);
}
void UnLock()
{
pthread_mutex_unlock(&_mtx);
}
bool TaskQueueIsEmpty()
{
return _task_queue.size()==0?true:false;
}
public:
bool _stop;//是否处于运行状态
private:
queue<Task> _task_queue;
int _num;//创建线程的数量
pthread_mutex_t _mtx;
pthread_cond_t _cond;
static ThreadPool* _sigleton;
};
ThreadPool* ThreadPool::_sigleton = nullptr;
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。