util/thread_pool.h
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | // SPDX-License-Identifier: BSD-3-Clause | ||
| 2 | #pragma once | ||
| 3 | |||
| 4 | #include <condition_variable> | ||
| 5 | #include <deque> | ||
| 6 | #include <functional> | ||
| 7 | #include <mutex> | ||
| 8 | #include <thread> | ||
| 9 | #include <vector> | ||
| 10 | |||
| 11 | namespace chrono::batch_render { | ||
| 12 | |||
| 13 | class ThreadPool { | ||
| 14 | public: | ||
| 15 | 385 | explicit ThreadPool(unsigned threads) : m_size(threads > 0 ? threads : 1) {} | |
| 16 | |||
| 17 | ~ThreadPool(); | ||
| 18 | ThreadPool(const ThreadPool&) = delete; | ||
| 19 | ThreadPool& operator=(const ThreadPool&) = delete; | ||
| 20 | |||
| 21 | void Add(const void* key, std::function<void()> job); | ||
| 22 | |||
| 23 | std::function<void()> Take(const void* key); | ||
| 24 | |||
| 25 | bool Cancel(const void* key); | ||
| 26 | |||
| 27 | private: | ||
| 28 | 5930 | struct Job { | |
| 29 | const void* key = nullptr; | ||
| 30 | std::function<void()> run; | ||
| 31 | }; | ||
| 32 | |||
| 33 | void Run(); | ||
| 34 | |||
| 35 | unsigned m_size; | ||
| 36 | std::mutex m_mutex; | ||
| 37 | std::deque<Job> m_jobs; | ||
| 38 | std::vector<std::thread> m_threads; | ||
| 39 | bool m_stopping = false; | ||
| 40 | std::condition_variable m_ready; | ||
| 41 | }; | ||
| 42 | |||
| 43 | } | ||
| 44 |