Loading...
Searching...
No Matches
loops_impl.h
1//
2// Copyright 2025 Pixar
3//
4// Licensed under the terms set forth in the LICENSE.txt file available at
5// https://openusd.org/license.
6//
7#ifndef PXR_BASE_WORK_TBB_LOOPS_IMPL_H
8#define PXR_BASE_WORK_TBB_LOOPS_IMPL_H
9
10#include "pxr/pxr.h"
11
12#include <tbb/blocked_range.h>
13#include <tbb/parallel_for.h>
14#include <tbb/parallel_for_each.h>
15#include <tbb/task_group.h>
16
17
21#define WORK_IMPL_HAS_PARALLEL_FOR_TBB_RANGE
22
23PXR_NAMESPACE_OPEN_SCOPE
24
29template <typename Fn>
30void
31WorkImpl_ParallelForN(size_t n, Fn &&callback, size_t grainSize)
32{
33 class Work_ParallelForN_TBB
34 {
35 public:
36 Work_ParallelForN_TBB(Fn &fn) : _fn(fn) { }
37
38 void operator()(const tbb::blocked_range<size_t> &r) const {
39 // Note that we std::forward _fn using Fn in order get the
40 // right operator().
41 // We maintain the right type in this way:
42 // If Fn is T&, then reference collapsing gives us T& for _fn
43 // If Fn is T, then std::forward correctly gives us T&& for _fn
44 std::forward<Fn>(_fn)(r.begin(), r.end());
45 }
46
47 private:
48 Fn &_fn;
49 };
50
51 // In most cases we do not want to inherit cancellation state from the
52 // parent context, so we create an isolated task group context.
53 tbb::task_group_context ctx(tbb::task_group_context::isolated);
54 tbb::parallel_for(tbb::blocked_range<size_t>(0,n,grainSize),
55 Work_ParallelForN_TBB(callback),
56 ctx);
57}
58
61template <typename RangeType, typename Fn>
62inline void
63WorkImpl_ParallelForTBBRange(const RangeType &range, Fn &&callback)
64{
65 tbb::task_group_context ctx(tbb::task_group_context::isolated);
66 tbb::parallel_for(range, std::forward<Fn>(callback), ctx);
67}
68
71template <typename InputIterator, typename Fn>
72inline void
73WorkImpl_ParallelForEach(
74 InputIterator first, InputIterator last, Fn &&fn)
75{
76 tbb::task_group_context ctx(tbb::task_group_context::isolated);
77 tbb::parallel_for_each(first, last, std::forward<Fn>(fn), ctx);
78}
79
80PXR_NAMESPACE_CLOSE_SCOPE
81
82#endif // PXR_BASE_WORK_TBB_LOOPS_IMPL_H