2021-10-12 14:20:30 +02:00
|
|
|
#pragma once
|
|
|
|
|
#include <thread>
|
|
|
|
|
#include <coroutine>
|
2021-10-23 00:22:35 +02:00
|
|
|
#include "Containers/List.h"
|
2021-10-12 14:20:30 +02:00
|
|
|
|
|
|
|
|
namespace Seele
|
|
|
|
|
{
|
2021-10-23 00:22:35 +02:00
|
|
|
struct JobPromise;
|
|
|
|
|
struct Event
|
2021-10-12 14:20:30 +02:00
|
|
|
{
|
2021-10-23 00:22:35 +02:00
|
|
|
public:
|
|
|
|
|
void raise()
|
|
|
|
|
{
|
|
|
|
|
flag.test_and_set();
|
|
|
|
|
flag.notify_all();
|
|
|
|
|
}
|
|
|
|
|
void reset()
|
|
|
|
|
{
|
|
|
|
|
flag.clear();
|
|
|
|
|
}
|
|
|
|
|
bool await_ready() { return flag.test(); }
|
|
|
|
|
void await_suspend(std::coroutine_handle<JobPromise> h);
|
|
|
|
|
void await_resume() {}
|
|
|
|
|
private:
|
|
|
|
|
std::atomic_flag flag;
|
2021-10-12 14:20:30 +02:00
|
|
|
};
|
|
|
|
|
struct [[nodiscard]] Job;
|
|
|
|
|
struct JobPromise
|
|
|
|
|
{
|
|
|
|
|
Job get_return_object() noexcept;
|
|
|
|
|
|
2021-10-23 00:22:35 +02:00
|
|
|
std::suspend_always initial_suspend() const noexcept { return {}; }
|
2021-10-12 14:20:30 +02:00
|
|
|
std::suspend_never final_suspend() const noexcept { return {}; }
|
|
|
|
|
|
|
|
|
|
void return_void() noexcept {}
|
|
|
|
|
void unhandled_exception() noexcept {
|
|
|
|
|
std::cerr << "Unhandled exception caught" << std::endl;
|
|
|
|
|
exit(1);
|
|
|
|
|
};
|
|
|
|
|
};
|
|
|
|
|
struct [[nodiscard]] Job
|
|
|
|
|
{
|
|
|
|
|
public:
|
|
|
|
|
using promise_type = JobPromise;
|
|
|
|
|
|
2021-10-23 00:22:35 +02:00
|
|
|
explicit Job(std::coroutine_handle<JobPromise> handle)
|
2021-10-12 14:20:30 +02:00
|
|
|
: handle(handle)
|
|
|
|
|
{}
|
|
|
|
|
~Job()
|
|
|
|
|
{
|
|
|
|
|
if(handle)
|
|
|
|
|
{
|
|
|
|
|
handle.destroy();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
private:
|
|
|
|
|
std::coroutine_handle<JobPromise> handle;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
class ThreadPool
|
|
|
|
|
{
|
|
|
|
|
public:
|
2021-10-23 00:22:35 +02:00
|
|
|
ThreadPool(uint32 threadCount = std::thread::hardware_concurrency());
|
2021-10-12 14:20:30 +02:00
|
|
|
virtual ~ThreadPool();
|
2021-10-23 00:22:35 +02:00
|
|
|
void addJob(Job&& job)
|
2021-10-12 14:20:30 +02:00
|
|
|
{
|
2021-10-23 00:22:35 +02:00
|
|
|
jobs.add(std::move(job));
|
2021-10-12 14:20:30 +02:00
|
|
|
}
|
|
|
|
|
private:
|
2021-10-23 00:22:35 +02:00
|
|
|
std::vector<std::thread> workers;
|
|
|
|
|
List<Job> jobs;
|
2021-10-12 14:20:30 +02:00
|
|
|
void threadLoop();
|
|
|
|
|
};
|
2021-10-23 00:22:35 +02:00
|
|
|
extern ThreadPool& getGlobalThreadPool();
|
2021-10-12 14:20:30 +02:00
|
|
|
} // namespace Seele
|