45 lines
934 B
C++
45 lines
934 B
C++
#include "Utils/ThreadPool.hpp"
|
|
#include "precomp.hpp"
|
|
|
|
namespace Chattr {
|
|
|
|
ThreadPool::ThreadPool(std::uint32_t numThreads) {
|
|
workers_.reserve(numThreads);
|
|
|
|
while (numThreads--)
|
|
workers_.push_back([this]() -> int { this->Worker(); return 1; });
|
|
}
|
|
|
|
ThreadPool::~ThreadPool() {
|
|
terminate_ = true;
|
|
jobQueueCV_.notify_all();
|
|
|
|
for (auto& t : workers_)
|
|
t.join();
|
|
}
|
|
|
|
void* ThreadPool::Worker() {
|
|
#ifdef _WIN32
|
|
DWORD pid = GetCurrentProcessId();
|
|
#elif __linux__
|
|
pid_t pid = getpid();
|
|
#endif
|
|
while (!terminate_) {
|
|
std::unique_lock<std::mutex> lock(jobQueueMutex);
|
|
spdlog::info("ThreadPool Worker : {} Waiting for a job", pid);
|
|
jobQueueCV_.wait(lock, [this]() { return !this->jobs_.empty() || terminate_; });
|
|
if (this->jobs_.empty())
|
|
return nullptr;
|
|
|
|
auto job = std::move(jobs_.front());
|
|
jobs_.pop();
|
|
lock.unlock();
|
|
|
|
spdlog::info("ThreadPool Worker : {} Executing a job", pid);
|
|
job();
|
|
}
|
|
|
|
return nullptr;
|
|
}
|
|
|
|
} |