Lagrange
All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Modules Pages
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
21namespace lagrange::poisson::threadpool {
22
24{
25 // Used to create thread-local data for map-reduce operations
26 static unsigned int NumThreads(void) { return tbb::this_task_arena::max_concurrency(); }
27
28 // Execute multiple functions in parallel
29 template <typename... Functions>
30 static void ParallelSections(Functions&&... funcs)
31 {
32 tbb::parallel_invoke(std::forward<Functions>(funcs)...);
33 }
34
35 // Execute a function in parallel over a range of indices
36 template <typename Function>
37 static void ParallelFor(size_t begin, size_t end, Function&& func)
38 {
39 // Keeping this commented block for quick debugging of multithread issues.
40#if 0
41 int thread_index = 0;
42 for (size_t i = begin; i < end; ++i) {
43 func(thread_index, i);
44 }
45#else
46 tbb::parallel_for(
47 tbb::blocked_range<size_t>(begin, end),
48 [&](const tbb::blocked_range<size_t>& r) {
49 int thread_index = tbb::this_task_arena::current_thread_index();
50 la_debug_assert(thread_index != tbb::task_arena::not_initialized);
51 for (size_t i = r.begin(); i < r.end(); ++i) {
52 func(thread_index, i);
53 }
54 });
55
56#endif
57 }
58};
59
60} // namespace lagrange::poisson::threadpool
#define la_debug_assert(...)
Debug assertion check.
Definition: assert.h:189