Lagrange
Loading...
Searching...
No Matches
ThreadPool.h
1/*
2 * Copyright 2024 Adobe. All rights reserved.
3 * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License. You may obtain a copy
5 * of the License at http://www.apache.org/licenses/LICENSE-2.0
6 *
7 * Unless required by applicable law or agreed to in writing, software distributed under
8 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9 * OF ANY KIND, either express or implied. See the License for the specific language
10 * governing permissions and limitations under the License.
11 */
12
13#pragma once
14
15#include <lagrange/utils/assert.h>
16
17#include <tbb/parallel_for.h>
18#include <tbb/parallel_invoke.h>
19#include <tbb/task_arena.h>
20
21#include <functional>
22
23namespace lagrange::texproc::threadpool {
24
26{
27 // Used to create thread-local data for map-reduce operations
28 static unsigned int NumThreads(void) { return tbb::this_task_arena::max_concurrency(); }
29
30 // Execute multiple functions in parallel
31 template <typename... Functions>
32 static void ParallelSections(Functions&&... funcs)
33 {
34 tbb::parallel_invoke(std::forward<Functions>(funcs)...);
35 }
36
37 // Execute a function in parallel over a range of indices
38 template <typename Function>
39 static void ParallelFor(size_t begin, size_t end, Function&& func)
40 {
41 static const bool NeedsThreadIndex =
42 std::is_convertible_v<Function, std::function<void(unsigned int, size_t)>>;
43
44 // Keeping this commented block for quick debugging of multithread issues.
45#if 0
46 int thread_index = 0;
47 for (size_t i = begin; i < end; ++i) {
48 if constexpr (NeedsThreadIndex)
49 func(thread_index, i);
50 else
51 func(i);
52 }
53#else
54
55 tbb::parallel_for(
56 tbb::blocked_range<size_t>(begin, end),
57 [&](const tbb::blocked_range<size_t>& r) {
58 int thread_index = tbb::this_task_arena::current_thread_index();
59 la_debug_assert(thread_index != tbb::task_arena::not_initialized);
60 for (size_t i = r.begin(); i < r.end(); ++i) {
61 if constexpr (NeedsThreadIndex)
62 func(thread_index, i);
63 else
64 func(i);
65 }
66 });
67
68#endif
69 }
70};
71
72} // namespace lagrange::texproc::threadpool
#define la_debug_assert(...)
Debug assertion check.
Definition assert.h:194