Import multithreaded simulation core
This commit is contained in:
1 parent
c72c388fe9
commit
65686db1a1
4 files changed
+2239
No files matched your search
@@ -0,0 +1,56 @@
|
||||
#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
|
||||
Reference in new issue
Block a user