group2 0.1.0
CSE 125 Group 2
Loading...
Searching...
No Matches
Parallel.hpp
Go to the documentation of this file.
1
29
30#pragma once
31
32#include <SDL3/SDL.h>
33
34#include <algorithm>
35#include <atomic>
36#include <cstdlib>
37
38#if defined(GROUP2_HAVE_TBB)
39#include <execution>
40#endif
41
42namespace group2::perf
43{
44
64inline std::atomic<bool> parallelEnabled{true};
65
69inline constexpr std::size_t k_parallelThreshold = 64;
70
77{
78 const char* p = std::getenv("GROUP2_SERVER_PARALLEL");
79 const bool wantOff = p != nullptr && (p[0] == '0' || p[0] == 'f' || p[0] == 'F' || p[0] == 'n' || p[0] == 'N');
80 const bool wantOn = !wantOff;
81 parallelEnabled.store(wantOn, std::memory_order_release);
82#if defined(GROUP2_HAVE_TBB)
83 SDL_Log("[perf] parallel kernels: %s (TBB-backed; default ON, set GROUP2_SERVER_PARALLEL=0 to disable)",
84 wantOn ? "ENABLED" : "disabled");
85#else
86 SDL_Log("[perf] parallel kernels: sequential fallback (TBB not linked)");
87#endif
88}
89
94template <class Iter, class Fn>
95inline void parallelFor(Iter begin, Iter end, Fn&& fn)
96{
97#if defined(GROUP2_HAVE_TBB)
98 const auto distance = std::distance(begin, end);
99 if (parallelEnabled.load(std::memory_order_relaxed) && static_cast<std::size_t>(distance) >= k_parallelThreshold) {
100 std::for_each(std::execution::par_unseq, begin, end, std::forward<Fn>(fn));
101 return;
102 }
103#endif
104 std::for_each(begin, end, std::forward<Fn>(fn));
105}
106
107} // namespace group2::perf
Definition Parallel.hpp:43
void parallelFor(Iter begin, Iter end, Fn &&fn)
Call fn(*it) for every element in [begin, end).
Definition Parallel.hpp:95
std::atomic< bool > parallelEnabled
Master switch for parallel execution.
Definition Parallel.hpp:64
void initParallelFromEnv()
Initialize from environment.
Definition Parallel.hpp:76
constexpr std::size_t k_parallelThreshold
Minimum items below which parallelFor runs sequentially even when the master switch is on.
Definition Parallel.hpp:69