#ifndef _THREADPOOL_H
#define _THREADPOOL_H
#include <vector>
#include <queue>
#include <thread>
#include <iostream>
#include <condition_variable>
using namespace std;
template <typename T>
class threadPool
{
public:
threadPool(int threadNumber = 1);
~threadPool();
bool append(T* task);
static void* worker(void* arg);
public:
void threadPoolRun();
void threadPoolStop();
private:
queue<T*> taskQueue;
vector<thread> workThread;
std::mutex threadPoolMtx;
std::condition_variable threadPoolCv;
const int MAX_THREADS = 100;
bool stop;
};
template <typename T>
threadPool<T>::threadPool(int threadNumber) : stop(false)
{
if (threadNumber <= 0 || threadNumber > MAX_THREADS) {
throw exception();
}
for (int i = 0; i < threadNumber; i++) {
workThread.emplace_back(worker, this);
}
}
template <typename T>
inline threadPool<T>::~threadPool() {
{
unique_lock<std::mutex> unique(threadPoolMtx);
stop = true;
}
threadPoolCv.notify_all();
for (auto& wt : workThread) {
wt.join();
}
}
template <typename T>
bool threadPool<T>::append(T* task) {
unique_lock<mutex> unique(threadPoolMtx);
taskQueue.push(task);
unique.unlock();
threadPoolCv.notify_one();
return true;
}
template <typename T>
void* threadPool<T>::worker(void* arg) {
threadPool* pool = (threadPool*)arg;
pool->threadPoolRun();
return pool;
}
template <typename T>
void threadPool<T>::threadPoolRun() {
while (!stop) {
unique_lock<mutex> unique(this->threadPoolMtx);
while (this->taskQueue.empty()) {
this->threadPoolCv.wait(unique);
}
if (!(this->taskQueue.empty())) {
T* task = this->taskQueue.front();
this->taskQueue.pop();
if (task) {
task->process();
}
}
}
}
template <typename T>
void threadPool<T>::threadPoolStop() {
~threadPool();
}
#endif
main.cpp
#include<iostream>
#include"ThreadPool.h"
#include <string>
using namespace std;
class Task
{
public:
void process()
{
cout << "task" << endl;
std::cout << "id = " << this_thread::get_id() << std::endl;
//this_thread::sleep_for(chrono::seconds(1));
}
};
int main(void)
{
threadPool<Task> pool(100);
while (1) {
Task* task1 = new Task();
Task* task5 = new Task();
Task* task6 = new Task();
Task* task7 = new Task();
Task* task8 = new Task();
Task* task9 = new Task();
Task* task10 = new Task();
Task* task11 = new Task();
Task* task12 = new Task();
pool.append(task1);
pool.append(task5);
pool.append(task6);
pool.append(task7);
pool.append(task8);
pool.append(task9);
pool.append(task10);
pool.append(task11);
pool.append(task12);
cout << "task successful2! " << endl;
delete task1;
delete task5;
delete task6;
delete task7;
delete task8;
delete task9;
delete task10;
delete task11;
delete task12;
cout << "task successful3! " << endl;
}
}