Added basic job system for async
This commit is contained in:
25
Nuake/src/Threading/Job.cpp
Normal file
25
Nuake/src/Threading/Job.cpp
Normal 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
25
Nuake/src/Threading/Job.h
Normal 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;
|
||||
};
|
||||
}
|
||||
43
Nuake/src/Threading/JobSystem.h
Normal file
43
Nuake/src/Threading/JobSystem.h
Normal 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user