11#ifndef EIGEN_THREADPOOL_FORKJOIN_H
12#define EIGEN_THREADPOOL_FORKJOIN_H
15#include "./InternalHeaderCheck.h"
61class ForkJoinScheduler {
70 template <
typename DoFnType,
typename DoneFnType,
typename ThreadPoolEnv>
71 static void ParallelForAsync(Index start, Index end, Index granularity, DoFnType&& do_func, DoneFnType&& done,
72 ThreadPoolTempl<ThreadPoolEnv>* thread_pool) {
77 granularity = numext::maxi<Index>(granularity, 1);
78 thread_pool->Schedule([start, end, granularity, thread_pool, do_func = std::forward<DoFnType>(do_func),
79 done = std::forward<DoneFnType>(done)]() {
80 RunParallelFor(start, end, granularity, do_func, thread_pool);
88 template <
typename DoFnType,
typename ThreadPoolEnv>
89 static void ParallelFor(Index start, Index end, Index granularity, DoFnType&& do_func,
90 ThreadPoolTempl<ThreadPoolEnv>* thread_pool) {
91 if (start >= end)
return;
93 auto done = [&barrier]() { barrier.Notify(); };
94 ParallelForAsync(start, end, granularity, std::forward<DoFnType>(do_func), done, thread_pool);
100 template <
typename LeftType,
typename RightType,
typename ThreadPoolEnv>
101 static void ForkJoin(LeftType&& left_thunk, RightType&& right_thunk, ThreadPoolTempl<ThreadPoolEnv>* thread_pool) {
102 using Task =
typename ThreadPoolTempl<ThreadPoolEnv>::Task;
103 std::atomic<bool> right_done(
false);
104 auto execute_right = [&right_thunk, &right_done]() {
105 std::forward<RightType>(right_thunk)();
106 right_done.store(
true, std::memory_order_release);
108 thread_pool->Schedule(std::move(execute_right));
109 std::forward<LeftType>(left_thunk)();
111 while (!right_done.load(std::memory_order_acquire)) {
112 thread_pool->MaybeGetTask(&task);
113 if (task.f) task.f();
117 static Index ComputeMidpoint(Index start, Index end, Index granularity) {
123 const Index size = end - start;
124 const Index offset = numext::round_down(9 * (size + 1) / 16, granularity);
125 return start + offset;
128 template <
typename DoFnType,
typename ThreadPoolEnv>
129 static void RunParallelFor(Index start, Index end, Index granularity, DoFnType&& do_func,
130 ThreadPoolTempl<ThreadPoolEnv>* thread_pool) {
131 Index mid = ComputeMidpoint(start, end, granularity);
132 if ((end - start) < granularity || mid == start || mid == end) {
136 ForkJoin([start, mid, granularity, &do_func,
137 thread_pool]() { RunParallelFor(start, mid, granularity, do_func, thread_pool); },
138 [mid, end, granularity, &do_func, thread_pool]() {
139 RunParallelFor(mid, end, granularity, do_func, thread_pool);