57 lines
1.5 KiB
C++
57 lines
1.5 KiB
C++
#include "settlement/core/worker_pool.hpp"
|
|
|
|
#include <stdexcept>
|
|
|
|
namespace settlement {
|
|
|
|
WorkerPool::WorkerPool(std::size_t thread_count) {
|
|
if (thread_count < 2) {
|
|
throw std::invalid_argument("worker pool needs at least two threads");
|
|
}
|
|
workers_.reserve(thread_count);
|
|
try {
|
|
for (std::size_t index = 0; index < thread_count; ++index) {
|
|
workers_.emplace_back([this] { worker_loop(); });
|
|
}
|
|
} catch (...) {
|
|
{
|
|
std::lock_guard<std::mutex> lock(mutex_);
|
|
stopping_ = true;
|
|
}
|
|
work_available_.notify_all();
|
|
for (std::thread& worker : workers_) {
|
|
if (worker.joinable()) worker.join();
|
|
}
|
|
throw;
|
|
}
|
|
}
|
|
|
|
WorkerPool::~WorkerPool() {
|
|
{
|
|
std::lock_guard<std::mutex> lock(mutex_);
|
|
stopping_ = true;
|
|
}
|
|
work_available_.notify_all();
|
|
for (std::thread& worker : workers_) {
|
|
if (worker.joinable()) worker.join();
|
|
}
|
|
}
|
|
|
|
std::size_t WorkerPool::thread_count() const noexcept { return workers_.size(); }
|
|
|
|
void WorkerPool::worker_loop() {
|
|
for (;;) {
|
|
std::function<void()> task;
|
|
{
|
|
std::unique_lock<std::mutex> lock(mutex_);
|
|
work_available_.wait(lock, [this] { return stopping_ || !tasks_.empty(); });
|
|
if (stopping_ && tasks_.empty()) return;
|
|
task = std::move(tasks_.front());
|
|
tasks_.pop();
|
|
}
|
|
task();
|
|
}
|
|
}
|
|
|
|
} // namespace settlement
|