basic taskManager (thread pool)

This commit is contained in:
Blue 2023-09-19 21:25:38 -03:00
parent 78b7407368
commit ec63dc655b
Signed by: blue
GPG Key ID: 9B203B252A63EE38
3 changed files with 116 additions and 0 deletions

View File

@ -1,11 +1,13 @@
set(SOURCES
collection.cpp
loggable.cpp
taskmanager.cpp
)
set(HEADERS
collection.h
loggable.h
taskmanager.h
)
target_sources(${PROJECT_NAME} PRIVATE ${SOURCES})

80
src2/taskmanager.cpp Normal file
View File

@ -0,0 +1,80 @@
#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);
}

34
src2/taskmanager.h Normal file
View File

@ -0,0 +1,34 @@
#pragma once
#include <string>
#include <queue>
#include <vector>
#include <thread>
#include <mutex>
#include <condition_variable>
class TaskManager {
public:
typedef std::string Job;
TaskManager();
~TaskManager();
void start();
void stop();
void wait();
bool busy();
private:
void loop();
private:
bool running;
bool stopping;
uint32_t maxThreads;
uint32_t activeThreads;
std::queue<Job> queue;
std::mutex queueMutex;
std::condition_variable loopConditional;
std::condition_variable waitConditional;
std::vector<std::thread> threads;
};