clay-template/src/thread_pool.cpp
2025-09-23 16:05:06 +02:00

55 lines
1.2 KiB
C++

#include "thread_pool.h"
#include <algorithm>
#include <thread>
#include <utility>
namespace threading {
ThreadPool::ThreadPool() {
size_t const thread_count{ std::max(std::thread::hardware_concurrency() - 1, 1u) };
this->threads.reserve(thread_count);
for (size_t i{ 0 }; i < thread_count; ++i) {
this->threads.emplace_back(std::bind(&ThreadPool::ThreadFn, this));
}
}
ThreadPool::~ThreadPool() {
{ std::scoped_lock lock{ this->lock };
this->shutdown = true;
this->threadNotifier.notify_all();
}
for (std::thread &thread : this->threads) {
thread.join();
}
}
size_t ThreadPool::GetThreadCount() {
return this->threads.size();
}
void ThreadPool::ScheduleTask(TaskFunc fn) {
std::scoped_lock lock{ this->lock };
this->taskQueue.emplace(std::move(fn));
this->threadNotifier.notify_one();
}
void ThreadPool::ThreadFn() {
TaskFunc function;
for(;;) {
{ std::unique_lock<std::mutex> lock{ this->lock };
while (!this->shutdown && this->taskQueue.empty()) {
this->threadNotifier.wait(lock);
}
if (this->taskQueue.empty()) {
return;
}
function = std::move(this->taskQueue.front());
this->taskQueue.pop();
}
function.operator()();
}
}
ThreadPool tasks{};
}