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

55 lines
1.3 KiB
C
Raw Normal View History

2023-04-22 20:35:46 -04:00
/*
* 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>
2023-04-22 21:11:30 -04:00
#include <functional>
#include <queue>
2023-04-22 20:35:46 -04:00
namespace blt {
2023-04-22 21:11:30 -04:00
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
*/
2023-04-22 20:35:46 -04:00
class thread_pool {
private:
2023-04-22 21:11:30 -04:00
volatile bool halted;
int MAX_THREADS;
2023-04-24 16:14:37 -04:00
std::queue<std::function<void()>*> runQueue {};
2023-04-22 21:11:30 -04:00
std::vector<std::thread*> threads {};
std::mutex queueMutex {};
2023-04-22 20:35:46 -04:00
public:
2023-04-22 21:11:30 -04:00
explicit thread_pool(int maxThreads);
/**
* Attempts to start the thread_pool.
*/
void start();
2023-04-24 16:14:37 -04:00
void run(std::function<void()>* func);
2023-04-22 21:11:30 -04:00
void run(runnable* func);
void stop();
~thread_pool();
2023-04-22 20:35:46 -04:00
};
2023-04-22 21:11:30 -04:00
2023-04-22 20:35:46 -04:00
}
#endif //FINALPROJECT_THREADPOOL_H