#include "taskmanager.h" TaskManager::TaskManager() : running(false), stopping(false), maxThreads(std::thread::hardware_concurrency()), activeThreads(0), queue(), queueMutex(), loopConditional(), waitConditional(), threads() { threads.reserve(maxThreads); } TaskManager::~TaskManager() { stop(); } void TaskManager::start() { std::lock_guard lock(queueMutex); if (running) return; for (uint32_t i = 0; i < maxThreads; ++i) threads.emplace_back(&TaskManager::loop, this); running = true; } void TaskManager::stop() { std::unique_lock lock(queueMutex); 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; std::unique_lock lock(queueMutex); while (!stopping && queue.empty()) loopConditional.wait(lock); if (stopping) return; ++activeThreads; job = queue.front(); queue.pop(); lock.unlock(); //do the job lock.lock(); --activeThreads; lock.unlock(); waitConditional.notify_all(); } } bool TaskManager::busy() { std::lock_guard lock(queueMutex); return activeThreads == 0; } void TaskManager::wait() { std::unique_lock lock(queueMutex); while (activeThreads != 0) waitConditional.wait(lock); }