42 lines
1.0 KiB
C++
42 lines
1.0 KiB
C++
#pragma once
|
|
#include "Thread.hpp"
|
|
#include <vector>
|
|
#include <queue>
|
|
#include <functional>
|
|
#include <condition_variable>
|
|
#include <mutex>
|
|
#include <memory>
|
|
|
|
namespace Chattr {
|
|
|
|
class ThreadPool {
|
|
public:
|
|
ThreadPool(std::uint32_t numThreads);
|
|
~ThreadPool();
|
|
|
|
template<typename _Callable, typename... _Args>
|
|
requires ReturnsVoidPtr<_Callable, _Args...> && (!std::is_same_v<std::decay_t<_Callable>, Thread>)
|
|
int enqueueJob(_Callable&& __job, void* retVal, _Args&&... __args) {
|
|
if (terminate_) {
|
|
spdlog::error("Cannot run jobs on threads that terminating...");
|
|
return -1;
|
|
}
|
|
|
|
std::lock_guard<std::mutex> lock(jobQueueMutex);
|
|
auto boundFunc = std::bind(std::forward<_Callable>(__job), std::forward<_Args>(__args)...);
|
|
std::function<void*()> job(std::move(boundFunc));
|
|
jobs_.push(job, retVal);
|
|
jobQueueCV_.notify_one();
|
|
}
|
|
|
|
private:
|
|
void* Worker();
|
|
|
|
std::condition_variable jobQueueCV_;
|
|
std::mutex jobQueueMutex;
|
|
std::queue<std::pair<std::function<void*()>, void*>> jobs_;
|
|
std::vector<Chattr::Thread> workers_;
|
|
bool terminate_ = false;
|
|
};
|
|
|
|
} |