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