]> git.stg.codes - stg.git/blob - projects/stargazer/async_pool.cpp
Disable cppcheck for foreign libs by default.
[stg.git] / projects / stargazer / async_pool.cpp
1 #include "async_pool.h"
2
3 using STG::AsyncPool;
4
5 AsyncPool& STG::AsyncPoolST::instance()
6 {
7     static AsyncPool pool;
8     return pool;
9 }
10
11 void AsyncPool::start()
12 {
13     if (m_thread.joinable())
14         return;
15     m_thread = std::jthread([this](auto token){ run(std::move(token)); });
16 }
17
18 void AsyncPool::stop()
19 {
20     if (!m_thread.joinable())
21         return;
22     m_thread.request_stop();
23     m_cond.notify_all();
24 }
25
26 void AsyncPool::run(std::stop_token token) noexcept
27 {
28     while (true)
29     {
30         Queue tasks;
31         {
32             std::unique_lock lock(m_mutex);
33             m_cond.wait(lock, [this, &token](){ return !m_tasks.empty() || token.stop_requested(); });
34             if (token.stop_requested())
35                 return;
36             if (!m_tasks.empty())
37                 tasks.swap(m_tasks);
38         }
39         for (const auto& t : tasks)
40             t();
41     }
42 }