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 // Keeping this commented block for quick debugging of multithread issues.
42#if 0
43 int thread_index = 0;
44 for (size_t i = begin; i < end; ++i) {
45 func(thread_index, i);
46 }
47#else
48 static const bool NeedsThreadIndex =
49 std::is_convertible_v<Function, std::function<void(unsigned int, size_t)>>;
50
51 tbb::parallel_for(
52 tbb::blocked_range<size_t>(begin, end),
53 [&](const tbb::blocked_range<size_t>& r) {
54 int thread_index = tbb::this_task_arena::current_thread_index();
55 la_debug_assert(thread_index != tbb::task_arena::not_initialized);
56 for (size_t i = r.begin(); i < r.end(); ++i) {
57 if constexpr (NeedsThreadIndex)
58 func(thread_index, i);
59 else
60 func(i);
61 }
62 });
63
64#endif
65 }
66};
67
68} // namespace lagrange::texproc::threadpool
#define la_debug_assert(...)
Debug assertion check.
Definition assert.h:194