1 Star 0 Fork 0

杭电码农-NEO / HTTP-Web Server Project

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
ThreadPool.hpp 2.63 KB
一键复制 编辑 原始数据 按行查看 历史
#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;
C++
1
https://gitee.com/NEO_kou/http-web-server-project.git
git@gitee.com:NEO_kou/http-web-server-project.git
NEO_kou
http-web-server-project
HTTP-Web Server Project
master

搜索帮助