Loading...
Searching...
No Matches
TileParallel.h
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2#ifndef GPR_LINALG_TILE_PARALLEL_H_
3#define GPR_LINALG_TILE_PARALLEL_H_
4
5#include <algorithm>
6#include <atomic>
7#include <condition_variable>
8#include <cstddef>
9#include <exception>
10#include <functional>
11#include <memory>
12#include <mutex>
13#include <stdexcept>
14#include <thread>
15#include <vector>
16
17namespace gpr {
18namespace linalg {
19
21inline std::atomic<int>& tileThreadCount() noexcept
22{
23 static std::atomic<int> count{1};
24 return count;
25}
26
28inline void setTileThreads(int threads) noexcept
29{
30 tileThreadCount().store(std::max(1, threads));
31}
32
41class TilePool {
42public:
44 {
45 static TilePool pool;
46 return pool;
47 }
48
49 template <class F>
50 void run(long count, F&& fn)
51 {
52 runWith(tileThreadCount().load(), count, std::forward<F>(fn));
53 }
54
56 template <class F>
57 void runWith(int threads, long count, F&& fn)
58 {
59 if (count <= 0) return;
60 if (threads <= 1 || count == 1 || in_worker()) {
61 for (long i = 0; i < count; ++i)
62 fn(i);
63 return;
64 }
65 std::unique_lock<std::mutex> launch(launch_mutex_);
66 ensureWorkers(threads - 1);
67 const std::function<void(long)> job = [&fn](long i) { fn(i); };
68 {
69 std::lock_guard<std::mutex> lock(mutex_);
70 job_ = &job;
71 count_ = count;
72 next_.store(0);
73 error_ = nullptr;
74 // Only as many workers as there are items beyond the caller's own.
75 wanted_ = static_cast<int>(
76 std::min<long>({count - 1, static_cast<long>(workers_.size()),
77 static_cast<long>(threads - 1)}));
78 busy_ = wanted_;
79 ++generation_;
80 }
81 wake_.notify_all();
82 // Loops nested in an item run serially on the thread that owns it.
83 in_worker() = true;
84 drain();
85 in_worker() = false;
86 std::unique_lock<std::mutex> lock(mutex_);
87 idle_.wait(lock, [&] { return busy_ == 0; });
88 job_ = nullptr;
89 if (error_) std::rethrow_exception(error_);
90 }
91
101 template <class F>
102 void start(long count, F&& fn)
103 {
104 if (started_) throw std::logic_error("TilePool::start while started");
105 started_ = true;
106 pending_ = std::function<void(long)>(std::forward<F>(fn));
107 pending_count_ = count;
108 const int threads = tileThreadCount().load();
109 caller_was_worker_ = in_worker();
110 async_ = threads > 1 && count > 0 && !caller_was_worker_;
111 // Loops of the caller run serially on it until finish(), with or
112 // without workers.
113 in_worker() = true;
114 if (!async_) return;
115 launch_lock_ = std::unique_lock<std::mutex>(launch_mutex_);
116 ensureWorkers(threads - 1);
117 {
118 std::lock_guard<std::mutex> lock(mutex_);
119 job_ = &pending_;
120 count_ = count;
121 next_.store(0);
122 error_ = nullptr;
123 wanted_ = static_cast<int>(
124 std::min<long>({count, static_cast<long>(workers_.size()),
125 static_cast<long>(threads - 1)}));
126 busy_ = wanted_;
127 ++generation_;
128 }
129 wake_.notify_all();
130 }
131
133 void finish()
134 {
135 if (!started_) return;
136 started_ = false;
137 if (!async_) {
138 // Restores the caller's state when an item throws, too.
139 struct Restore {
140 bool value;
141 ~Restore()
142 {
143 in_worker() = value;
144 }
145 } restore{caller_was_worker_};
146 for (long i = 0; i < pending_count_; ++i)
147 pending_(i);
148 pending_ = nullptr;
149 return;
150 }
151 drain();
152 in_worker() = caller_was_worker_;
153 std::unique_lock<std::mutex> lock(mutex_);
154 idle_.wait(lock, [&] { return busy_ == 0; });
155 job_ = nullptr;
156 lock.unlock();
157 pending_ = nullptr;
158 launch_lock_.unlock();
159 if (error_) std::rethrow_exception(error_);
160 }
161
163 {
164 {
165 std::lock_guard<std::mutex> lock(mutex_);
166 stop_ = true;
167 ++generation_;
168 }
169 wake_.notify_all();
170 for (std::thread& worker: workers_)
171 worker.join();
172 }
173
174 TilePool(const TilePool&) = delete;
175 TilePool& operator=(const TilePool&) = delete;
176
177private:
178 TilePool() = default;
179
180 static bool& in_worker() noexcept
181 {
182 thread_local bool flag = false;
183 return flag;
184 }
185
186 void ensureWorkers(int wanted)
187 {
188 while (static_cast<int>(workers_.size()) < wanted) {
189 const int id = static_cast<int>(workers_.size());
190 workers_.emplace_back([this, id] { workerLoop(id); });
191 }
192 }
193
194 void drain()
195 {
196 for (;;) {
197 const long i = next_.fetch_add(1);
198 if (i >= count_) return;
199 try {
200 (*job_)(i);
201 } catch (...) {
202 std::lock_guard<std::mutex> lock(mutex_);
203 if (!error_) error_ = std::current_exception();
204 next_.store(count_);
205 }
206 }
207 }
208
209 void workerLoop(int id)
210 {
211 in_worker() = true;
212 unsigned long seen = 0;
213 for (;;) {
214 {
215 std::unique_lock<std::mutex> lock(mutex_);
216 wake_.wait(lock, [&] { return generation_ != seen; });
217 seen = generation_;
218 if (stop_) return;
219 if (id >= wanted_) continue;
220 }
221 drain();
222 {
223 std::lock_guard<std::mutex> lock(mutex_);
224 --busy_;
225 }
226 idle_.notify_all();
227 }
228 }
229
230 std::mutex launch_mutex_;
231 std::mutex mutex_;
232 std::condition_variable wake_;
233 std::condition_variable idle_;
234 std::vector<std::thread> workers_;
235 const std::function<void(long)>* job_ = nullptr;
236 long count_ = 0;
237 std::atomic<long> next_{0};
238 int wanted_ = 0;
239 int busy_ = 0;
240 unsigned long generation_ = 0;
241 bool stop_ = false;
242 std::exception_ptr error_;
243 std::function<void(long)> pending_;
244 long pending_count_ = 0;
245 bool started_ = false;
246 bool async_ = false;
247 bool caller_was_worker_ = false;
248 std::unique_lock<std::mutex> launch_lock_;
249};
250
254public:
255 template <class F>
256 TileBackground(long count, F&& fn)
257 {
258 TilePool::instance().start(count, std::forward<F>(fn));
259 }
260 void finish()
261 {
263 }
265 {
266 try {
268 } catch (...) {
269 }
270 }
273};
274
276template <class F>
277inline void parallelFor(long count, F&& fn)
278{
279 TilePool::instance().run(count, std::forward<F>(fn));
280}
281
282} // namespace linalg
283} // namespace gpr
284
285#endif // GPR_LINALG_TILE_PARALLEL_H_
TileBackground(const TileBackground &)=delete
TileBackground(long count, F &&fn)
TileBackground & operator=(const TileBackground &)=delete
void start(long count, F &&fn)
TilePool & operator=(const TilePool &)=delete
void finish()
Joins the items of start(); see there.
void runWith(int threads, long count, F &&fn)
run() with an explicit thread count in place of the configured one.
TilePool(const TilePool &)=delete
void run(long count, F &&fn)
static TilePool & instance()
Dense and structured linear algebra behind the GP: Cholesky and eigen solvers, linear operators,...
void setTileThreads(int threads) noexcept
Sets the tile thread count (at least one).
void parallelFor(long count, F &&fn)
parallelFor(count, fn): see TilePool::run.
std::atomic< int > & tileThreadCount() noexcept
Number of threads one rank devotes to independent tile products.
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16