2021-09-18 22:08:46 +02:00
|
|
|
#pragma once
|
|
|
|
|
|
|
|
namespace big
|
|
|
|
{
|
2023-08-03 12:56:05 +02:00
|
|
|
// if this limit is hit you did something wrong coding wise.
|
|
|
|
constexpr auto MAX_POOL_SIZE = 32u;
|
|
|
|
|
2023-04-04 23:52:57 +02:00
|
|
|
struct thread_pool_job
|
|
|
|
{
|
|
|
|
std::function<void()> m_func;
|
|
|
|
std::source_location m_source_location;
|
|
|
|
};
|
|
|
|
|
2021-09-18 22:08:46 +02:00
|
|
|
class thread_pool
|
|
|
|
{
|
|
|
|
std::atomic<bool> m_accept_jobs;
|
|
|
|
std::condition_variable m_data_condition;
|
|
|
|
|
2023-04-04 23:52:57 +02:00
|
|
|
std::stack<thread_pool_job> m_job_stack;
|
2021-09-18 22:08:46 +02:00
|
|
|
std::mutex m_lock;
|
|
|
|
std::vector<std::thread> m_thread_pool;
|
|
|
|
|
2023-10-31 20:21:40 +01:00
|
|
|
// the amount of threads active in the pool
|
2023-08-03 12:56:05 +02:00
|
|
|
std::atomic<size_t> m_allocated_thread_count;
|
2023-10-31 20:21:40 +01:00
|
|
|
// the amount of threads currently on a job
|
|
|
|
std::atomic<size_t> m_busy_threads;
|
2023-04-04 23:52:57 +02:00
|
|
|
|
2021-09-18 22:08:46 +02:00
|
|
|
public:
|
2023-08-03 12:56:05 +02:00
|
|
|
// YimMenu only has 2 blocking threads, 4 should be sufficient but the pool should automatically allocate more if needed
|
|
|
|
thread_pool(const std::size_t preallocated_thread_count = 4);
|
2021-09-18 22:08:46 +02:00
|
|
|
~thread_pool();
|
|
|
|
|
|
|
|
void destroy();
|
2023-04-04 23:52:57 +02:00
|
|
|
void push(std::function<void()> func, std::source_location location = std::source_location::current());
|
2023-03-01 21:27:15 +00:00
|
|
|
|
2023-10-31 20:21:40 +01:00
|
|
|
std::pair<size_t, size_t> usage() const
|
|
|
|
{ return { m_busy_threads, m_allocated_thread_count }; }
|
|
|
|
|
2021-09-18 22:08:46 +02:00
|
|
|
private:
|
|
|
|
void run();
|
2023-08-03 12:56:05 +02:00
|
|
|
void rescale_thread_pool();
|
2021-09-18 22:08:46 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
inline thread_pool* g_thread_pool{};
|
2023-04-04 23:52:57 +02:00
|
|
|
}
|