Added basic job system for async

This commit is contained in:
Antoine Pilote
2024-03-10 13:00:34 -04:00
parent f18be64eae
commit ccdb305b54
5 changed files with 108 additions and 4 deletions

View File

@@ -53,6 +53,7 @@
#include <src/Resource/StaticResources.h>
#include <src/Scripting/ScriptingEngineNet.h>
#include <src/Threading/JobSystem.h>
namespace Nuake {
@@ -127,10 +128,14 @@ namespace Nuake {
{
if (ImGui::Button(ICON_FA_PLAY, ImVec2(30, 30)) || (Input::IsKeyPressed(GLFW_KEY_F5)))
{
SceneSnapshot = Engine::GetCurrentScene()->Copy();
this->SceneSnapshot = Engine::GetCurrentScene()->Copy();
ScriptingEngineNet::Get().BuildProjectAssembly(Engine::GetProject());
Engine::EnterPlayMode();
auto job = [this]()
{
ScriptingEngineNet::Get().BuildProjectAssembly(Engine::GetProject());
};
JobSystem::Get().Dispatch(job, []() { Engine::EnterPlayMode(); });
}
if (ImGui::BeginItemTooltip())
@@ -240,7 +245,12 @@ namespace Nuake {
if (ImGui::Button(ICON_FA_HAMMER, ImVec2(30, 30)))
{
Nuake::ScriptingEngineNet::Get().BuildProjectAssembly(Engine::GetProject());
JobSystem::Get().Dispatch([]()
{
Nuake::ScriptingEngineNet::Get().BuildProjectAssembly(Engine::GetProject());
},
[]() {}
);
}
if (ImGui::BeginItemTooltip())

View File

@@ -3,6 +3,7 @@
#include "src/Core/Logger.h"
#include "src/Core/FileSystem.h"
#include "src/Core/OS.h"
#include "src/Threading/JobSystem.h"
#include "src/Resource/Project.h"
#include "src/Scene/Components/NetScriptComponent.h"

View File

@@ -0,0 +1,25 @@
#include "Job.h"
namespace Nuake {
Job::Job(std::function<void()> job, std::function<void()> end)
: m_Job(job)
, m_End(end)
{
m_End = end;
m_Thread = std::thread([this, job]()
{
job();
m_IsDone = true;
});
}
void Job::End()
{
if (m_End)
{
m_End();
}
}
}

25
Nuake/src/Threading/Job.h Normal file
View File

@@ -0,0 +1,25 @@
#pragma once
#include <atomic>
#include <functional>
#include <thread>
namespace Nuake {
class Job
{
public:
Job(std::function<void()> job, std::function<void()> end);
Job(const Job&) = delete;
Job& operator=(const Job&) = delete;
~Job() { m_Thread.join(); }
bool IsDone() { return m_IsDone; }
void End();
private:
std::thread m_Thread;
std::atomic<bool> m_IsDone;
std::function<void()> m_Job;
std::function<void()> m_End;
};
}

View File

@@ -0,0 +1,43 @@
#pragma once
#include "Job.h"
namespace Nuake {
class JobSystem
{
private:
std::vector<std::unique_ptr<Job>> m_Jobs;
public:
JobSystem() = default;
~JobSystem() = default;
static JobSystem& Get()
{
static JobSystem instance;
return instance;
}
void Dispatch(std::function<void()> job, std::function<void()> end)
{
m_Jobs.push_back(std::make_unique<Job>(job, end));
}
void Update()
{
for (auto it = m_Jobs.begin(); it != m_Jobs.end();)
{
if (it->get()->IsDone())
{
it->get()->End();
it = m_Jobs.erase(it);
}
else
{
++it;
}
}
}
};
}