58 {
59
60
61
62
63 const std::size_t tasks_per_thread = grain ==
Grain::Coarse ? 1 : 8;
64 if (concurrency_ <= 1 ||
65 count < static_cast<std::size_t>(concurrency_) * tasks_per_thread) {
66 for (std::size_t index = 0; index < count; ++index)
67 operation(index);
68 return;
69 }
70#ifdef GPR_HAVE_OPENBLAS
71 const int saved_blas = openblas_get_num_threads();
72 if (saved_blas > 1) openblas_set_num_threads(1);
73#endif
74#ifdef GPR_USE_STDPAR
75 std::vector<std::size_t> indices(count);
76 std::iota(indices.begin(), indices.end(), std::size_t{0});
77 std::vector<std::exception_ptr> failures(count);
78 tbb::task_arena arena(concurrency_);
79 arena.execute([&] {
80 std::for_each(std::execution::par, indices.begin(), indices.end(),
81 [&](std::size_t index) noexcept {
82 try {
83 operation(index);
84 } catch (...) {
85 failures[index] = std::current_exception();
86 }
87 });
88 });
89 for (const auto& failure: failures)
90 if (failure) std::rethrow_exception(failure);
91#elif defined(USE_OPENMP)
92 std::vector<std::exception_ptr> failures(count);
93#pragma omp parallel for schedule(static) num_threads(concurrency_)
94 for (long index = 0; index < static_cast<long>(count); ++index) {
95 try {
96 operation(static_cast<std::size_t>(index));
97 } catch (...) {
98 failures[static_cast<std::size_t>(index)] =
99 std::current_exception();
100 }
101 }
102 for (const auto& failure: failures)
103 if (failure) std::rethrow_exception(failure);
104#else
105 for (std::size_t index = 0; index < count; ++index)
106 operation(index);
107#endif
108#ifdef GPR_HAVE_OPENBLAS
109 if (saved_blas > 1) openblas_set_num_threads(saved_blas);
110#endif
111 }