64 lines
1.3 KiB
C++
64 lines
1.3 KiB
C++
#include "Utils/ThreadPool.hpp"
|
|
#include "precomp.hpp"
|
|
|
|
namespace Chattr {
|
|
|
|
ThreadPool::ThreadPool() {
|
|
}
|
|
|
|
ThreadPool::ThreadPool(std::uint32_t numThreads) {
|
|
init(numThreads);
|
|
}
|
|
|
|
ThreadPool::~ThreadPool() {
|
|
terminate_ = true;
|
|
jobQueueCV_.notify_all();
|
|
|
|
for (auto& t : workers_)
|
|
t.join();
|
|
}
|
|
|
|
void ThreadPool::init(std::uint32_t numThreads) {
|
|
int numCPU = numThreads;
|
|
if (numThreads == 0) {
|
|
#ifdef _WIN32
|
|
SYSTEM_INFO sysinfo;
|
|
GetSystemInfo(&sysinfo);
|
|
numCPU = sysinfo.dwNumberOfProcessors;
|
|
#elif __linux__
|
|
numCPU = sysconf(_SC_NPROCESSORS_ONLN);
|
|
#endif
|
|
spdlog::info("Auto-detected cpu count: {}", numCPU);
|
|
spdlog::info("Set ThreadPool Worker count to: {}", numCPU);
|
|
}
|
|
workers_.reserve(numCPU);
|
|
|
|
while (numCPU--)
|
|
workers_.push_back([this]() { this->Worker(); });
|
|
}
|
|
|
|
void* ThreadPool::Worker() {
|
|
#ifdef _WIN32
|
|
DWORD pid = GetCurrentThreadId();
|
|
#elif __linux__
|
|
pthread_t pid = pthread_self();
|
|
#endif
|
|
spdlog::info("ThreadPool Worker : {} up.", pid);
|
|
while (!terminate_) {
|
|
std::unique_lock<std::mutex> lock(jobQueueMutex);
|
|
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;
|
|
}
|
|
|
|
} |