Debian Codegraph @

include/deal.II/base/lazy.h

raw
1 // ------------------------------------------------------------------------
2 //
3 // SPDX-License-Identifier: LGPL-2.1-or-later
4 // Copyright (C) 2023 - 2024 by the deal.II authors
5 //
6 // This file is part of the deal.II library.
7 //
8 // Part of the source code is dual licensed under Apache-2.0 WITH
9 // LLVM-exception OR LGPL-2.1-or-later. Detailed license information
10 // governing the source code and code contributions can be found in
11 // LICENSE.md and CONTRIBUTING.md at the top level directory of deal.II.
12 //
13 // ------------------------------------------------------------------------
14
15 #ifndef dealii_lazy_h
16 #define dealii_lazy_h
17
18
19 #include <deal.II/base/config.h>
20
21 #include <deal.II/base/exceptions.h>
22 #include <deal.II/base/memory_consumption.h>
23 #include <deal.II/base/mutex.h>
24 #include <deal.II/base/task_result.h>
25
26 #include <atomic>
27 #include <mutex>
28 #include <optional>
29 #include <type_traits>
30
31
32 DEAL_II_NAMESPACE_OPEN
33
34 /**
35 * @addtogroup threads
36 * @{
37 */
38
39 /**
40 * This class is a wrapper that provides a convenient mechanism for lazy
41 * initialization of the contained object on first use. The class ensures
42 * that on-demand initialization of some expensive data structure happens
43 * (a) exactly once in a thread-safe manner, and that (b) subsequent checks
44 * in hot paths are cheap.
45 *
46 * Lazy<T> is closely modeled after the `std::optional` interface providing
47 * a `reset()` and `value()` method, but also and extending it with two
48 * methods: `ensure_initialized(creator)` which, as the name suggests,
49 * ensures that the contained object is properly initialized. If the
50 * `Lazy<T>` happens happens to contain no value yet, it initializes the
51 * wrapped object by calling the `creator()` function object and storing
52 * the return value. In addition a `value_or_initialize(creator)` function
53 * is provided that, similarly, ensures that the object is properly
54 * initialized and then returns a reference to the contained value.
55 *
56 * Example usage could look like the following, where the `FE` class stores a
57 * matrix that is expensive to compute and so we do not want to do it unless it
58 * is actually needed. As a consequence, rather than storing a matrix, we store
59 * a `Lazy<FullMatrix<double>>` that by default is empty; whenever the matrix is
60 * first requested, we create it and store it for later reuse:
61 * ```
62 * template<...>
63 * class FE
64 * {
65 * public:
66 * const FullMatrix<double> & get_prolongation_matrix() const
67 * {
68 * prolongation_matrix.ensure_initialized([&](){
69 * // Some expensive operation initializing the prolongation matrix
70 * // that we only want to perform once and when necessary.
71 * });
72 * return prolongation_matrix.value();
73 * }
74 *
75 * private:
76 * Lazy<FullMatrix<double>> prolongation_matrix;
77 * };
78 * ```
79 *
80 * @note Conceptually, this class is not so different from
81 * [std::future](https://en.cppreference.com/w/cpp/thread/future), which
82 * can also be used to represent a possibly-not-yet-available value on which
83 * one can wait when used with the "deferred" policy of
84 * [std::async](https://en.cppreference.com/w/cpp/thread/async).
85 * In particular, the following code could be used in place
86 * of the one above:
87 * ```
88 * template<...>
89 * class FE
90 * {
91 * public:
92 * FE () {
93 * prolongation_matrix = std::async(std::launch::deferred,
94 * [&](){
95 * // Some expensive operation initializing the prolongation matrix
96 * // that we only want to perform once and when necessary.
97 * });
98 * }
99 *
100 * FullMatrix<double> get_prolongation_matrix() const
101 * {
102 * return prolongation_matrix.get();
103 * }
104 *
105 * private:
106 * std::future<FullMatrix<double>> prolongation_matrix;
107 * };
108 * ```
109 * The difference to what Lazy does is that for Lazy, the action must be
110 * specified in the place where we want to access the deferred computation's
111 * result. In contrast, in the scheme with `std::future` and `std::async`,
112 * the action has to be provided at the point where the `std::future`
113 * object is initialized. Both are valid approaches and, depending on
114 * context, can usefully be employed. The difference is simply in what
115 * kind of information the provided lambda function can capture: Is it
116 * the environment available at the time the constructor is run, or the
117 * environment available at the time the access function is run. The latter
118 * has the advantage that the information captured is always up to date,
119 * whereas in the scheme with `std::async`, one has to be careful not to
120 * capture information in the lambda function that could be changed by later
121 * calls to member functions but before the lambda function is finally
122 * evaluated in the getter function. (There is another difference:
123 * `std::future::get()` can only be called once, as the function returns
124 * the computed object by value and may move the object out of its internal
125 * storage. As a consequence, the call to `FE::get_prolongation_matrix()`
126 * is only valid the first time around. Lazy does not have this restriction.)
127 *
128 * @dealiiConceptRequires{std::is_move_constructible_v<T> &&
129 std::is_move_assignable_v<T >}
130 */
131 template <typename T>
132 DEAL_II_CXX20_REQUIRES((std::is_move_constructible_v<T> &&
133 std::is_move_assignable_v<T>))
134 class Lazy
135 {
136 public:
137 /**
138 * Default Constructor.
139 */
140 Lazy();
141
142
143 /**
144 * Copy constructor. If the `other` object contains an initialized
145 * value, then that value will be copied into the current object. If the
146 * `other` object is uninitialized, then the current object will be as well.
147 */
148 Lazy(const Lazy &other);
149
150
151 /**
152 * Move constructor. If the `other` object contains an initialized
153 * value, then that value will be moved into the current object, and the
154 * `other` object will end up being empty (as if default initialized). If the
155 * `other` object is uninitialized, then the current object will be as well.
156 */
157 Lazy(Lazy &&other) noexcept;
158
159
160 /**
161 * Copy assignment. If the `other` object contains an initialized
162 * value, then that value will be copied into the current object. If the
163 * `other` object is uninitialized, then the current object will be as well.
164 *
165 * Any content of the current object is lost in the assignment.
166 */
167 Lazy &
168 operator=(const Lazy &other);
169
170
171 /**
172 * Move assignment. If the `other` object contains an initialized
173 * value, then that value will be moved into the current object, and the
174 * `other` object will end up being empty (as if default initialized). If the
175 * `other` object is uninitialized, then the current object will be as well.
176 *
177 * Any content of the current object is lost in the move assignment.
178 */
179 Lazy &
180 operator=(Lazy &&other) noexcept;
181
182
183 /**
184 * Reset the Lazy<T> object to an uninitialized state.
185 */
186 void
187 reset() noexcept;
188
189
190 /**
191 * Initialize the wrapped object.
192 *
193 * If the contained object is already initialized this function simply
194 * returns and does nothing.
195 *
196 * If, instead, the object has not yet been initialized then the @p
197 * creator function object (oftentimes a lambda function) is called to
198 * initialize the contained object.
199 *
200 * This operation is thread safe: The ensure_initialized() method
201 * guarantees that the creator function object is only called once on one
202 * of the calling threads and that after completion the initialization
203 * result (which is stored in the std::optional) is visible on all
204 * threads.
205 *
206 * @dealiiConceptRequires{std::is_invocable_r_v<T, Callable>}
207 */
208 template <typename Callable>
209 void
210 ensure_initialized(const Callable &creator) const
211 DEAL_II_CXX20_REQUIRES((std::is_invocable_r_v<T, Callable>));
212
213
214 /**
215 * Returns true if the contained object has been initialized, otherwise
216 * false.
217 */
218 bool
219 has_value() const;
220
221
222 /**
223 * Return a const reference to the contained object.
224 *
225 * @pre The object has been initialized with a call to
226 * ensure_initialized() or value_or_initialized().
227 */
228 const T &
229 value() const;
230
231
232 /**
233 * If the underlying object is initialized the function simply returns a
234 * const reference to the contained value. Otherwise, the @p creator()
235 * function object is called to initialize the object first.
236 *
237 * This function mimics the syntax of the std::optional<T> interface and
238 * is functionally equivalent to calling ensure_initialized() followed by
239 * value(). It returns a `const` reference to make clear that the object
240 * created by the `creator` function is what it is, and is not subject
241 * to later modification unless one calls reset() and creates a new
242 * object.
243 *
244 * @post The underlying object is initialized, meaning, has_value()
245 * returns true.
246 *
247 * @dealiiConceptRequires{std::is_invocable_r_v<T, Callable>}
248 */
249 template <typename Callable>
250 const T &
251 value_or_initialize(const Callable &creator) const
252 DEAL_II_CXX20_REQUIRES((std::is_invocable_r_v<T, Callable>));
253
254 /**
255 * Compute the memory consumption of this structure.
256 */
257 std::size_t
258 memory_consumption() const;
259
260 private:
261 /**
262 * A handle to the task used to create the lazily initialized object.
263 */
264 mutable Threads::TaskResult<T> task_result;
265
266
267 /**
268 * An atomic bool used for checking whether the object is initialized in
269 * a thread-safe manner.
270 */
271 mutable std::atomic<bool> object_is_initialized;
272 };
273
274 /**
275 * @}
276 */
277
278
279 // ------------------------------- inline functions --------------------------
280
281 #ifndef DOXYGEN
282
283 template <typename T>
284 DEAL_II_CXX20_REQUIRES((std::is_move_constructible_v<T> &&
285 std::is_move_assignable_v<T>))
286 inline Lazy<T>::Lazy()
287 : object_is_initialized(false)
288 {}
289
290
291
292 template <typename T>
293 DEAL_II_CXX20_REQUIRES((std::is_move_constructible_v<T> &&
294 std::is_move_assignable_v<T>))
295 inline Lazy<T>::Lazy(const Lazy &other)
296 {
297 // If the other object has a value stored, then get it and set our
298 // own object to a copy of it:
299 if (other.has_value())
300 {
301 object_is_initialized.store(true);
302 task_result.emplace_object(other.value());
303 }
304 else
305 object_is_initialized.store(false);
306 }
307
308
309
310 template <typename T>
311 DEAL_II_CXX20_REQUIRES((std::is_move_constructible_v<T> &&
312 std::is_move_assignable_v<T>))
313 inline Lazy<T>::Lazy(Lazy &&other) noexcept
314 : task_result(std::move(other.task_result))
315 {
316 object_is_initialized.store(other.object_is_initialized.load());
317
318 // Mark the other object as uninitialized.
319 other.object_is_initialized.store(false);
320 }
321
322
323
324 template <typename T>
325 DEAL_II_CXX20_REQUIRES((std::is_move_constructible_v<T> &&
326 std::is_move_assignable_v<T>))
327 inline Lazy<T> &Lazy<T>::operator=(const Lazy &other)
328 {
329 // If the other object has a value stored, then get it and set our
330 // own object to a copy of it:
331 if (other.has_value())
332 {
333 object_is_initialized.store(true);
334 task_result.emplace_object(other.value());
335 }
336 else
337 {
338 object_is_initialized.store(false);
339 task_result.clear();
340 }
341
342 return *this;
343 }
344
345
346
347 template <typename T>
348 DEAL_II_CXX20_REQUIRES((std::is_move_constructible_v<T> &&
349 std::is_move_assignable_v<T>))
350 inline Lazy<T> &Lazy<T>::operator=(Lazy &&other) noexcept
351 {
352 task_result = std::move(other.task_result);
353 object_is_initialized.store(other.object_is_initialized.load());
354
355 // Mark the other object as uninitialized.
356 other.object_is_initialized.store(false);
357
358 return *this;
359 }
360
361
362
363 template <typename T>
364 DEAL_II_CXX20_REQUIRES((std::is_move_constructible_v<T> &&
365 std::is_move_assignable_v<T>))
366 inline void Lazy<T>::reset() noexcept
367 {
368 object_is_initialized.store(false);
369 task_result.clear();
370 }
371
372
373 template <typename T>
374 DEAL_II_CXX20_REQUIRES((std::is_move_constructible_v<T> &&
375 std::is_move_assignable_v<T>))
376 template <typename Callable>
377 inline DEAL_II_ALWAYS_INLINE
378 void Lazy<T>::ensure_initialized(const Callable &creator) const
379 DEAL_II_CXX20_REQUIRES((std::is_invocable_r_v<T, Callable>))
380 {
381 //
382 // Use Schmidt's double checking [1] for checking and initializing the
383 // object.
384 //
385 // [1] https://en.wikipedia.org/wiki/Double-checked_locking
386 //
387
388 //
389 // Check the object_is_initialized atomic with "acquire" semantics [1].
390 //
391 // This ensures that (a) all subsequent reads (of the object) are
392 // ordered after this check, and that (b) all writes to the object
393 // before the atomic bool was set to true with "release" semantics are
394 // visible on this thread.
395 //
396 // [1]
397 // https://en.cppreference.com/w/cpp/atomic/memory_order#Release-Acquire_ordering
398 //
399 if (!object_is_initialized.load(std::memory_order_acquire))
400 # ifdef DEAL_II_HAVE_CXX20
401 [[unlikely]]
402 # endif
403 {
404 // Check again. If this thread won the race to the lock then we
405 // would like to initialize the object. Otherwise another thread has
406 // already initialized the object and flipped the object_is_initialized
407 // bit. (Here, the initialization_mutex ensures consistent ordering
408 // with a memory fence, so we will observe the updated bool without
409 // acquire semantics.)
410 //
411 // Naively, we should think that we can check again for
412 // object_is_initialized to be true, and if it is false just execute
413 // the 'creator' function object. The problem with this approach is that
414 // if we have N worker threads and spawn N+1 tasks that all want to
415 // end querying the Lazy object, then N will be run right away of which
416 // N-1 will block. The one remaining task will have gotten into the
417 // locked section and run the 'creator' object. But if the 'creator'
418 // itself spawns tasks, the scheduler may decide to first execute
419 // the (N+1)st task from above which will then promptly get stuck
420 // here as well -- and we're in a deadlock situation.
421 //
422 // The solution to the problem is to use a scheme whereby the
423 // work we do in setting up 'creator' cannot block, and where we block
424 // below is in a context where it's the *scheduler* that blocks to ensure
425 // that it can continue to schedule tasks.
426 //
427 // This is what TaskResult::try_emplace_task() does:
428 if (!object_is_initialized.load(std::memory_order_relaxed))
429 task_result.try_emplace_task(creator);
430
431 // At this point, either this or another thread have emplaced a
432 // task and we wait for it to complete. If we do need to wait, then
433 // the waiting happens in the task scheduler, which can run other
434 // tasks in the meantime, ensuring progress:
435 task_result.join();
436
437 // At this point, we know that the task has completed (whether set by
438 // this or another thread), and we can flip the object_is_initialized
439 // boolean with "release" semantics [1].
440 //
441 // This ensures that the above move is visible on all threads
442 // before checking the atomic bool with acquire semantics.
443 // If another thread that had also been waiting in the join() call
444 // above has gotten here first and set the flag to 'true', that
445 // ok.
446 object_is_initialized.store(true, std::memory_order_release);
447 }
448
449 Assert(has_value(),
450 ExcMessage("The current object does not contain a valid object "
451 "even though we have just initialized it."));
452 }
453
454
455 template <typename T>
456 DEAL_II_CXX20_REQUIRES((std::is_move_constructible_v<T> &&
457 std::is_move_assignable_v<T>))
458 inline DEAL_II_ALWAYS_INLINE bool Lazy<T>::has_value() const
459 {
460 //
461 // In principle it would be sufficient to solely check the atomic<bool>
462 // object_is_initialized because the load() is performed with "acquire"
463 // semantics. But just in case let's check the object.has_value() boolean
464 // as well:
465 //
466 return (object_is_initialized && (task_result.empty() == false));
467 }
468
469
470 template <typename T>
471 DEAL_II_CXX20_REQUIRES((std::is_move_constructible_v<T> &&
472 std::is_move_assignable_v<T>))
473 inline DEAL_II_ALWAYS_INLINE const T &Lazy<T>::value() const
474 {
475 Assert(
476 has_value(),
477 ExcMessage(
478 "value() has been called but the contained object has not been "
479 "initialized. Did you forget to call 'ensure_initialized()' first?"));
480
481 return task_result.value();
482 }
483
484
485 template <typename T>
486 DEAL_II_CXX20_REQUIRES((std::is_move_constructible_v<T> &&
487 std::is_move_assignable_v<T>))
488 template <typename Callable>
489 inline DEAL_II_ALWAYS_INLINE const T &Lazy<T>::value_or_initialize(
490 const Callable &creator) const
491 DEAL_II_CXX20_REQUIRES((std::is_invocable_r_v<T, Callable>))
492 {
493 ensure_initialized(creator);
494 return task_result.value();
495 }
496
497
498 template <typename T>
499 DEAL_II_CXX20_REQUIRES((std::is_move_constructible_v<T> &&
500 std::is_move_assignable_v<T>))
501 std::size_t Lazy<T>::memory_consumption() const
502 {
503 return MemoryConsumption::memory_consumption(task_result) + //
504 sizeof(*this) - sizeof(task_result);
505 }
506
507 #endif
508
509 DEAL_II_NAMESPACE_CLOSE
510 #endif