XNetwork 1.7.5; VERSION ${PROJECT_VERSION}
Loading...
Searching...
No Matches
thread_pool.hpp
Go to the documentation of this file.
1#pragma once
2
23#include <condition_variable>
24#include <functional>
25#include <future>
26#include <memory>
27#include <mutex>
28#include <queue>
29#include <thread>
30#include <type_traits>
31#include <utility>
32
33namespace xnetwork {
34
36 public:
41 explicit thread_pool(size_t num_threads = std::thread::hardware_concurrency())
42 : stop_(false) {
43 if (num_threads == 0) {
44 num_threads = 1;
45 }
46 workers_.reserve(num_threads);
47 for (size_t i = 0; i < num_threads; ++i) {
48 workers_.emplace_back([this] { worker_loop(); });
49 }
50 }
51
53 {
54 std::lock_guard<std::mutex> lock(queue_mutex_);
55 stop_ = true;
56 }
57 condition_.notify_all();
58 for (auto& w : workers_) {
59 if (w.joinable()) {
60 w.join();
61 }
62 }
63 }
64
65 thread_pool(const thread_pool&) = delete;
69
77 template <typename F> auto enqueue(F&& task)
78 -> std::future<std::invoke_result_t<std::decay_t<F>>> {
79 using return_type = std::invoke_result_t<std::decay_t<F>>;
80
81 auto packaged
82 = std::make_shared<std::packaged_task<return_type()>>(std::forward<F>(task));
83
84 auto future = packaged->get_future();
85 {
86 std::lock_guard<std::mutex> lock(queue_mutex_);
87 if (stop_) {
88 throw std::runtime_error("enqueue on stopped thread_pool");
89 }
90 tasks_.emplace([packaged]() { (*packaged)(); });
91 }
92 condition_.notify_one();
93 return future;
94 }
95
96 private:
97 void worker_loop() {
98 while (true) {
99 std::function<void()> task;
100 {
101 std::unique_lock<std::mutex> lock(queue_mutex_);
102 condition_.wait(lock, [this] { return stop_ || !tasks_.empty(); });
103 if (stop_ && tasks_.empty()) {
104 return;
105 }
106 task = std::move(tasks_.front());
107 tasks_.pop();
108 }
109 task();
110 }
111 }
112
113 std::vector<std::thread> workers_;
114 std::queue<std::function<void()>> tasks_;
115 std::mutex queue_mutex_;
116 std::condition_variable condition_;
117 bool stop_;
118 };
119
120} // namespace xnetwork
Read-only map of maps of maps (view into a dict-of-dict-of-dict structure)
Definition coreviews.hpp:109
Definition thread_pool.hpp:35
~thread_pool()
Definition thread_pool.hpp:52
thread_pool(size_t num_threads=std::thread::hardware_concurrency())
Definition thread_pool.hpp:41
thread_pool(thread_pool &&)=delete
thread_pool & operator=(const thread_pool &)=delete
thread_pool(const thread_pool &)=delete
thread_pool & operator=(thread_pool &&)=delete
auto enqueue(F &&task) -> std::future< std::invoke_result_t< std::decay_t< F > > >
Definition thread_pool.hpp:77
Definition digraphs.hpp:24