1 Star 5 Fork 2

Jhao / 学习C++,项目高并发内存池与自主实现HTTP服务器

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
ThreadPool.hpp 2.13 KB
一键复制 编辑 原始数据 按行查看 历史
Jhao 提交于 2022-07-31 10:18 . 自主实现HTTP服务器
#pragma once
#include<pthread.h>
#include"Task.hpp"
#include<queue>
#define NUM 5
//基于阻塞队列的线程池
class ThreadPool{
private:
pthread_mutex_t mtx;
pthread_cond_t cond;
std::queue<Task> q;
static ThreadPool* inst;
ThreadPool()
{
pthread_mutex_init(&mtx,nullptr);
pthread_cond_init(&cond,nullptr);
}
ThreadPool(const ThreadPool&) = delete;
ThreadPool& operator=(const ThreadPool&) = delete;
public:
static ThreadPool* GetInstance()
{
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
if(inst == nullptr)
{
pthread_mutex_lock(&lock);
if(inst == nullptr)
{
//创建线程池并初始化
inst = new ThreadPool;
inst->InitThreadPool();
}
pthread_mutex_unlock(&lock);
}
return inst;
}
void ThreadWait()
{
pthread_cond_wait(&cond,&mtx);
}
void ThreadWakeup()
{
pthread_cond_signal(&cond);
}
void Lock()
{
pthread_mutex_lock(&mtx);
}
void Unlock()
{
pthread_mutex_unlock(&mtx);
}
bool IsEmpty()
{
return q.empty();
}
Task& Front()
{
return q.front();
}
void Pop()
{
return q.pop();
}
static void* ThreadRun(void* args)
{
ThreadPool* tp = (ThreadPool*) args;
while(1)
{
tp->Lock();
while(tp->IsEmpty())
{
tp->ThreadWait();
}
Task& t = tp->Front();
tp->Pop();
tp->Unlock();
//在外面处理任务
t();
}
}
void PutTask(const Task& t)
{
Lock();
q.push(t);
ThreadWakeup();
Unlock();
}
void InitThreadPool()
{
for(int i = 0;i < NUM;++i)
{
pthread_t tid;
if(pthread_create(&tid,nullptr,ThreadRun,this) != 0)
{
LOG(FATAL,"create ThreadPool fail!");
}
pthread_detach(tid);
}
LOG(INFO,"InitThreadPool");
}
~ThreadPool()
{
pthread_mutex_destroy(&mtx);
pthread_cond_destroy(&cond);
}
};
ThreadPool* ThreadPool::inst = nullptr;
1
https://gitee.com/wuyi-ljh/test-43---testing.git
git@gitee.com:wuyi-ljh/test-43---testing.git
wuyi-ljh
test-43---testing
学习C++,项目高并发内存池与自主实现HTTP服务器
master

搜索帮助