hp-FEM
Adaptive hp-FEM suite for nano-optics
Loading...
Searching...
No Matches
parallel.hpp
Go to the documentation of this file.
1#pragma once
7
8#include <atomic>
9#include <exception>
10#include <utility>
11
12#ifdef _OPENMP
13#include <omp.h>
14#endif
15
16#include "hpfem/core/types.hpp"
17
18namespace hpfem {
19
21[[nodiscard]] bool has_openmp() noexcept;
23[[nodiscard]] int num_threads() noexcept;
26void set_num_threads(int threads) noexcept;
28[[nodiscard]] inline int thread_index() noexcept {
29#ifdef _OPENMP
30 return omp_get_thread_num();
31#else
32 return 0;
33#endif
34}
35
40template <class Body>
41void parallel_for(Index n, Body&& body) {
42#ifdef _OPENMP
43 std::atomic<bool> failed{false};
44 std::exception_ptr error;
45#pragma omp parallel for schedule(dynamic, 8)
46 for (Index i = 0; i < n; ++i) {
47 if (failed.load(std::memory_order_relaxed)) continue;
48 try {
49 body(i, omp_get_thread_num());
50 } catch (...) {
51#pragma omp critical(hpfem_parallel_for_error)
52 {
53 if (!failed.exchange(true)) error = std::current_exception();
54 }
55 }
56 }
57 if (error) std::rethrow_exception(error);
58#else
59 for (Index i = 0; i < n; ++i) body(i, 0);
60#endif
61}
62
63} // namespace hpfem
Definition axisymmetric_estimator.hpp:39
void set_num_threads(int threads) noexcept
int num_threads() noexcept
Number of threads a parallel loop uses (1 without OpenMP).
void parallel_for(Index n, Body &&body)
Definition parallel.hpp:41
std::int64_t Index
global indices (DoFs, entities)
Definition types.hpp:17
int thread_index() noexcept
Index of the calling thread inside a parallel loop, 0 outside.
Definition parallel.hpp:28
bool has_openmp() noexcept
True if the library was built with OpenMP.