代码拉取完成,页面将自动刷新
#pragma once
#include "LockGuard.hpp"
#include "Thread.hpp"
#include "Log.hpp"
#include <vector>
#include <queue>
#include <unistd.h>
#define THREAD_NUM 5
template <class T>
class ThreadPool
{
public:
void waitCond()
{
pthread_cond_wait(&_cond, &_lock);
}
pthread_mutex_t *getMutex()
{
return &_lock;
}
T getTask()
{
T t = _task_queue.front();
_task_queue.pop();
return t;
}
bool empty()
{
return _task_queue.empty();
}
// 测试
void joins()
{
for (auto &it : _threads)
{
it->join();
}
}
private:
ThreadPool(int thread_num = THREAD_NUM)
: _num(thread_num)
{
pthread_mutex_init(&_lock, nullptr);
pthread_cond_init(&_cond, nullptr);
for (int i = 1; i <= _num; i++)
{
_threads.push_back(new Thread(i, routine, this));
}
}
ThreadPool(const ThreadPool<T> &other) = delete;
const ThreadPool<T> &operator=(const ThreadPool<T> &other) = delete;
public:
static ThreadPool<T> *getThreadPool(int num = THREAD_NUM)
{
if (_thread_ptr == nullptr)
{
LockGuard Lockguard(&_mutex);
if (_thread_ptr == nullptr)
{
_thread_ptr = new ThreadPool<T>(num);
}
}
return _thread_ptr;
}
public:
~ThreadPool()
{
for (auto &it : _threads)
{
it->join();
delete it;
}
pthread_mutex_destroy(&_lock);
pthread_cond_destroy(&_cond);
}
// 线程执行任务
void run()
{
for (auto &it : _threads)
{
it->start();
logMessage(NORMAL, "%s %s", it->name().c_str(), "启动成功");
}
}
// 将任务入队列
void pushTask(const T &task)
{
LockGuard LockGuard(&_lock);
_task_queue.push(task);
pthread_cond_signal(&_cond);
}
// 线程函数
static void *routine(void *args)
{
ThreadData *td = (ThreadData *)args;
ThreadPool<T> *tp = (ThreadPool<T> *)td->_args;
while (1)
{
T task;
{
LockGuard LockGuard(tp->getMutex());
while (tp->empty())
{
tp->waitCond();
}
// 读取任务
task = tp->getTask(); // 任务[共享空间]->获取[私有空间]
}
task(td->_name); // 执行任务
}
}
private:
std::vector<Thread *> _threads; // 保存线程的数组
std::queue<T> _task_queue; // 保存任务的队列
int _num; // 线程的个数
pthread_mutex_t _lock; // 互斥锁
pthread_cond_t _cond; // 条件变量
static ThreadPool<T> *_thread_ptr; // 保存单例对象的地址
static pthread_mutex_t _mutex; // 单例模式的全局互斥锁
};
template <typename T>
ThreadPool<T> *ThreadPool<T>::_thread_ptr = nullptr; // 初始化指针
template <typename T>
pthread_mutex_t ThreadPool<T>::_mutex = PTHREAD_MUTEX_INITIALIZER; // 初始化互斥锁
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。