Files
Seele/src/Engine/ThreadPool.cpp
T

67 lines
1.4 KiB
C++
Raw Normal View History

2021-10-12 14:20:30 +02:00
#include "ThreadPool.h"
using namespace Seele;
2023-12-17 16:16:46 +01:00
ThreadPool::ThreadPool(uint32 numWorkers)
2021-12-15 00:05:42 +01:00
{
2023-12-17 16:16:46 +01:00
for (uint32 i = 0; i < numWorkers; ++i)
2022-03-28 21:18:57 +02:00
{
2023-12-17 16:16:46 +01:00
workers.add(std::thread(&ThreadPool::work, this));
2021-11-01 20:25:16 +01:00
}
2021-10-12 14:20:30 +02:00
}
2021-10-23 00:22:35 +02:00
ThreadPool::~ThreadPool()
2021-10-12 14:20:30 +02:00
{
2022-03-26 12:55:04 +01:00
{
2023-12-17 16:16:46 +01:00
std::unique_lock l(taskLock);
running = false;
taskCV.notify_all();
2022-03-26 12:55:04 +01:00
}
2023-12-17 16:16:46 +01:00
for (auto& worker : workers)
2022-03-26 12:55:04 +01:00
{
worker.join();
}
2022-02-14 16:29:26 +01:00
}
2023-12-17 16:16:46 +01:00
void ThreadPool::runAndWait(List<std::function<void()>> functions)
2022-02-14 16:29:26 +01:00
{
2022-01-12 14:40:26 +01:00
{
2023-12-17 16:16:46 +01:00
std::unique_lock l(taskLock);
currentTask.numRemaining = functions.size();
currentTask.functions = std::move(functions);
taskCV.notify_all();
2022-01-12 14:40:26 +01:00
}
2023-12-17 16:16:46 +01:00
while (currentTask.numRemaining > 0)
2021-11-19 15:08:56 +01:00
{
2023-12-17 16:16:46 +01:00
std::unique_lock l2(completedLock);
completedCV.wait(l2);
2022-03-19 22:45:30 +01:00
}
}
2023-12-17 16:16:46 +01:00
void ThreadPool::work()
2022-03-19 22:45:30 +01:00
{
2023-12-17 16:16:46 +01:00
while (true)
2022-03-19 22:45:30 +01:00
{
2023-12-17 16:16:46 +01:00
std::unique_lock l(taskLock);
while(currentTask.functions.empty())
2022-03-19 22:45:30 +01:00
{
2023-12-17 16:16:46 +01:00
taskCV.wait(l);
if (!running)
{
return;
}
2021-11-19 15:08:56 +01:00
}
2023-12-17 16:16:46 +01:00
auto func = std::move(currentTask.functions.front());
currentTask.functions.popFront();
l.unlock();
func();
l.lock();
currentTask.numRemaining--;
if (currentTask.numRemaining == 0)
2021-11-19 15:08:56 +01:00
{
2023-12-17 16:16:46 +01:00
std::unique_lock l2(completedLock);
completedCV.notify_one();
2021-11-24 12:10:23 +01:00
}
2021-11-01 20:25:16 +01:00
}
}