VWeb/Source/ThreadPool.cpp

45 lines
1.1 KiB
C++
Raw Normal View History

2022-08-23 14:13:21 +02:00
#include <VWeb.h>
#include <thread>
2023-09-02 14:17:56 +02:00
#include <utility>
2022-08-23 14:13:21 +02:00
namespace VWeb {
2023-09-02 14:17:56 +02:00
ThreadPool::ThreadPool(std::string name) : m_Name(std::move(name)) {}
2022-08-23 14:13:21 +02:00
void ThreadPool::Create() {
if (m_IsCreated)
return;
m_IsDone = false;
m_IsCreated = true;
m_Queue.Open();
for (int i = 0; i < m_ThreadCount; ++i) {
2023-09-02 14:17:56 +02:00
m_Threads.emplace_back(&ThreadPool::Execute, this);
}
printf("[ThreadPool] >> Created %d Threads for Pool \"%s\"\n", m_ThreadCount,
m_Name.c_str());
2022-08-23 14:13:21 +02:00
}
void ThreadPool::Stop() {
m_IsDone = true;
m_Queue.Flush();
for (int i = 0; i < m_ThreadCount; ++i)
m_Threads[i].join();
}
void ThreadPool::Dispatch(const Ref<WorkerJob> &job) { m_Queue.Push(job); }
void ThreadPool::SetThreadCount(int count) {
if (m_IsCreated)
return;
m_ThreadCount =
count == -1 ? (int)std::thread::hardware_concurrency() : count;
}
void ThreadPool::Execute() {
if (!m_IsCreated)
return;
while (auto queueItem = m_Queue.WaitAndPop()) {
if (!queueItem.has_value() || m_Queue.IsClosed())
continue;
auto &item = queueItem.value();
if (item == nullptr)
continue;
item->Execute();
}
}
} // namespace VWeb