X-Git-Url: https://git.stg.codes/stg.git/blobdiff_plain/1c529746ff07312e30e76fd933c628c658e3c77d..646c8fd6c0112573ba2aae7f165f5d48e849831e:/projects/stargazer/async_pool.h diff --git a/projects/stargazer/async_pool.h b/projects/stargazer/async_pool.h new file mode 100644 index 00000000..cf82db0d --- /dev/null +++ b/projects/stargazer/async_pool.h @@ -0,0 +1,62 @@ +#pragma once + +#include +#include +#include +#include +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wshadow" +#include +#pragma GCC diagnostic pop +#include + +namespace STG +{ + +class AsyncPool +{ + public: + AsyncPool() = default; + + void start(); + void stop(); + + template + void enqueue(F&& f) + { + { + std::lock_guard lock(m_mutex); + m_tasks.emplace_back(std::forward(f)); + } + m_cond.notify_all(); + } + + private: + using Task = std::function; + using Queue = std::deque; + + std::mutex m_mutex; + std::condition_variable m_cond; + Queue m_tasks; + std::jthread m_thread; + + void run(std::stop_token token) noexcept; +}; + +namespace AsyncPoolST +{ + +AsyncPool& instance(); + +inline +void start() { instance().start(); } +inline +void stop() { instance().stop(); } + +template +inline +void enqueue(F&& f) { instance().enqueue(std::forward(f)); } + +}; + +}