1 Star 0 Fork 0

无敌最俊朗/outstanding_code

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
threadPool.hpp 2.70 KB
一键复制 编辑 原始数据 按行查看 历史
无敌最俊朗 提交于 9个月前 . reactor done
#pragma once
#include <iostream>
#include <vector>
#include <queue>
#include <pthread.h>
#include <unistd.h>
#include "Thread.hpp"
#include "Log.hpp"
using namespace ThreadModel;
const static int gdefaultthreadnum = 3;
// 日志
template <typename T>
class ThreadPool
{
private:
void LockQueue()
{
pthread_mutex_lock(&_mutex);
}
void UnlockQueue()
{
pthread_mutex_unlock(&_mutex);
}
void ThreadSleep()
{
pthread_cond_wait(&_cond, &_mutex);
}
void ThreadWakeup()
{
pthread_cond_signal(&_cond);
}
void ThreadWakeupAll()
{
pthread_cond_broadcast(&_cond);
}
public:
ThreadPool(int threadnum = gdefaultthreadnum) : _threadnum(threadnum), _waitnum(0), _isrunning(false)
{
pthread_mutex_init(&_mutex, nullptr);
pthread_cond_init(&_cond, nullptr);
}
~ThreadPool()
{
pthread_mutex_destroy(&_mutex);
pthread_cond_destroy(&_cond);
}
void HandlerTask(std::string name)
{
while (true)
{
sleep(1);
LockQueue();
while (_task_queue.empty() && _isrunning)
{
_waitnum++;
ThreadSleep();
_waitnum--;
}
if (_task_queue.empty() && !_isrunning)
{
UnlockQueue();
break;
}
T t = _task_queue.front();
_task_queue.pop();
UnlockQueue();
t();
}
}
bool Enqueue(const T &t)
{
LOG(INFO,"task%s","~");
bool ret = false;
LockQueue();
if (_isrunning)
{
_task_queue.push(t);
if (_waitnum > 0)
{
ThreadWakeup();
}
ret = true;
}
UnlockQueue();
return ret;
}
void InitThreadPool()
{
for (int i = 0; i < _threadnum; i++)
{
std::string name = "thread-" + std::to_string(i + 1);
_threads.emplace_back(std::bind(&ThreadPool::HandlerTask, this, std::placeholders::_1), name);
}
_isrunning = true;
}
void Start()
{
for (auto &thread : _threads)
{
thread.Start();
}
}
void Wait()
{
for (auto &thread : _threads)
{
thread.Join();
}
}
void Stop()
{
LockQueue();
_isrunning = false;
ThreadWakeupAll();
UnlockQueue();
}
private:
int _threadnum;
std::vector<Thread> _threads; // for fix, int temp
std::queue<T> _task_queue;
pthread_mutex_t _mutex;
pthread_cond_t _cond;
int _waitnum;
bool _isrunning;
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/zuijunlang/outstanding_code.git
git@gitee.com:zuijunlang/outstanding_code.git
zuijunlang
outstanding_code
outstanding_code
master

搜索帮助