COSC-3P98-Final-Project/include/util/threadpool.h

55 lines
1.3 KiB
C++

/*
* Created by Brett on 22/04/23.
* Licensed under GNU General Public License V3.0
* See LICENSE file for license detail
*/
#ifndef FINALPROJECT_THREADPOOL_H
#define FINALPROJECT_THREADPOOL_H
#include <thread>
#include <mutex>
#include <functional>
#include <queue>
namespace blt {
class runnable {
public:
virtual void run() = 0;
virtual ~runnable() = default;
};
/**
* If your runnable functions are small consider using another data structure,
* as thread_pool will be slow if many small tasks are needed to be ran.
* thread_pool is designed for running large long run tasks
*/
class thread_pool {
private:
volatile bool halted;
int MAX_THREADS;
std::queue<std::function<void()>*> runQueue {};
std::vector<std::thread*> threads {};
std::mutex queueMutex {};
public:
explicit thread_pool(int maxThreads);
/**
* Attempts to start the thread_pool.
*/
void start();
void run(std::function<void()>* func);
void run(runnable* func);
void stop();
~thread_pool();
};
}
#endif //FINALPROJECT_THREADPOOL_H