23#include <condition_variable>
42 explicit thread_pool(
size_t num_threads = std::thread::hardware_concurrency()) {
43 if (num_threads == 0) {
46 workers_.reserve(num_threads);
47 for (
size_t i = 0; i < num_threads; ++i) {
48 workers_.emplace_back([
this] { worker_loop(); });
54 std::lock_guard<std::mutex> lock(queue_mutex_);
57 condition_.notify_all();
58 for (
auto& w : workers_) {
65 [[nodiscard]]
auto size() const ->
size_t {
return workers_.size(); }
79 template <
typename F>
auto enqueue(F&& task)
80 -> std::future<std::invoke_result_t<std::decay_t<F>>> {
81 using return_type = std::invoke_result_t<std::decay_t<F>>;
84 = std::make_shared<std::packaged_task<return_type()>>(std::forward<F>(task));
86 auto future = packaged->get_future();
88 std::lock_guard<std::mutex> lock(queue_mutex_);
90 throw std::runtime_error(
"enqueue on stopped thread_pool");
92 tasks_.emplace([packaged]() { (*packaged)(); });
94 condition_.notify_one();
101 std::function<void()> task;
103 std::unique_lock<std::mutex> lock(queue_mutex_);
104 condition_.wait(lock, [
this] {
return stop_ || !tasks_.empty(); });
105 if (stop_ && tasks_.empty()) {
108 task = std::move(tasks_.front());
115 std::vector<std::thread> workers_;
116 std::queue<std::function<void()>> tasks_;
117 std::mutex queue_mutex_;
118 std::condition_variable condition_;
131 static thread_pool pool(std::thread::hardware_concurrency());
Definition thread_pool.hpp:35
thread_pool & operator=(thread_pool &&)=delete
~thread_pool()
Definition thread_pool.hpp:52
thread_pool(size_t num_threads=std::thread::hardware_concurrency())
Construct a thread pool with the given number of worker threads.
Definition thread_pool.hpp:42
thread_pool(thread_pool &&)=delete
thread_pool & operator=(const thread_pool &)=delete
auto enqueue(F &&task) -> std::future< std::invoke_result_t< std::decay_t< F > > >
Definition thread_pool.hpp:79
thread_pool(const thread_pool &)=delete
auto size() const -> size_t
Definition thread_pool.hpp:65
Options for convergence-based algorithms.
Definition aberth.hpp:13
auto get_thread_pool() -> thread_pool &
Convenience accessor returning a singleton thread pool.
Definition thread_pool.hpp:130