mason/src2/taskmanager.cpp

88 lines
1.6 KiB
C++
Raw Normal View History

2023-09-20 00:25:38 +00:00
#include "taskmanager.h"
TaskManager::TaskManager() :
running(false),
stopping(false),
maxThreads(std::thread::hardware_concurrency()),
activeThreads(0),
2023-09-20 19:45:22 +00:00
jobs(),
mutex(),
2023-09-20 00:25:38 +00:00
loopConditional(),
waitConditional(),
threads()
{
threads.reserve(maxThreads);
}
TaskManager::~TaskManager() {
stop();
}
2023-09-20 19:45:22 +00:00
void TaskManager::queue(const Job& job) {
std::unique_lock lock(mutex);
jobs.emplace(job);
lock.unlock();
loopConditional.notify_one();
}
2023-09-20 00:25:38 +00:00
void TaskManager::start() {
2023-09-20 19:45:22 +00:00
std::lock_guard lock(mutex);
2023-09-20 00:25:38 +00:00
if (running)
return;
for (uint32_t i = 0; i < maxThreads; ++i)
threads.emplace_back(&TaskManager::loop, this);
running = true;
}
void TaskManager::stop() {
2023-09-20 19:45:22 +00:00
std::unique_lock lock(mutex);
2023-09-20 00:25:38 +00:00
if (!running)
return;
stopping = true;
lock.unlock();
loopConditional.notify_all();
for (std::thread& thread : threads)
thread.join();
threads.clear();
}
void TaskManager::loop() {
while (true) {
Job job;
2023-09-20 19:45:22 +00:00
std::unique_lock lock(mutex);
while (!stopping && jobs.empty())
2023-09-20 00:25:38 +00:00
loopConditional.wait(lock);
if (stopping)
return;
++activeThreads;
2023-09-20 19:45:22 +00:00
job = jobs.front();
jobs.pop();
2023-09-20 00:25:38 +00:00
lock.unlock();
2023-09-20 19:45:22 +00:00
job();
2023-09-20 00:25:38 +00:00
lock.lock();
--activeThreads;
lock.unlock();
waitConditional.notify_all();
}
}
2023-09-20 19:45:22 +00:00
bool TaskManager::busy() const {
std::lock_guard lock(mutex);
2023-09-20 00:25:38 +00:00
return activeThreads == 0;
}
2023-09-20 19:45:22 +00:00
void TaskManager::wait() const {
std::unique_lock lock(mutex);
2023-09-20 00:25:38 +00:00
while (activeThreads != 0)
waitConditional.wait(lock);
}