#include <iostream>
#include <pthread.h>
#include <vector>
#include <queue>
#include <unistd.h>
#include "thread.hpp"
#include "lockGuard.hpp"
#include "log.hpp"
const int default_capacity = 5;
template <class T>
class ThreadPool
{
private:
// 构造函数
ThreadPool(int capacity = default_capacity)
: _capacity(capacity)
{
pthread_mutex_init(&_mtx, nullptr);
pthread_cond_init(&_cond, nullptr);
for (int i = 0; i < capacity; i++)
{
Thread *ptd = new Thread(i + 1, routine, this);
_threads.push_back(ptd);
}
}
// 拷贝构造函数
ThreadPool(const ThreadPool<T> &other) = delete;
// 赋值运算符
const ThreadPool<T> &operator=(const ThreadPool<T> &other) = delete;
public:
static ThreadPool<T> *getInstance(int capacity = default_capacity)
{
if (thread_ptr == nullptr)
{
lockGuard lockguard(&mutex);
if (thread_ptr == nullptr)
{
thread_ptr = new ThreadPool<T>(capacity);
}
}
return thread_ptr;
}
bool isEmpty()
{
return _task_queue.empty();
}
static void *routine(void *arg)
{
ThreadData *td = (ThreadData *)arg;
ThreadPool<T> *tp = (ThreadPool<T> *)td->_args;
while (true)
{
lockGuard lockguard(&tp->_mtx);
if (tp->isEmpty())
{
pthread_cond_wait(&tp->_cond, &tp->_mtx);
}
T task = tp->_task_queue.front();
tp->_task_queue.pop();
task(td->_name);
sleep(1);
}
}
void run()
{
for (auto &iter : _threads)
{
iter->start();
// std::cout << iter->name() << " 启动成功" << std::endl;
logMessage(NORMAL, "%s%s", iter->name().c_str(), "启动成功");
}
}
void pushTask(const T &task)
{
lockGuard lockguard(&_mtx);
_task_queue.push(task);
pthread_cond_signal(&_cond);
}
void joins()
{
for (int i = 0; i < _capacity; i++)
{
_threads[i]->join();
}
}
~ThreadPool()
{
for (int i = 0; i < _capacity; i++)
{
_threads[i]->join();
delete _threads[i];
}
pthread_mutex_destroy(&_mtx);
pthread_cond_destroy(&_cond);
}
private:
std::vector<Thread *> _threads; // 存放线程
size_t _capacity;
std::queue<T> _task_queue; // 存放任务
pthread_mutex_t _mtx;
pthread_cond_t _cond;
static ThreadPool<T> *thread_ptr; // 声明
static pthread_mutex_t mutex;
};
template <class T>
static ThreadPool<T> *ThreadPool<T>::thread_ptr = nullptr;
template <class T>
static pthread_mutex_t ThreadPool<T>::mutex = PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP;
线程池单例化
最新推荐文章于 2024-06-07 19:44:58 发布