Loading...
Searching...
No Matches
loops.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_H
8#define PXR_BASE_WORK_TBB_LOOPS_H
9
11#include "pxr/pxr.h"
12
13#include <tbb/blocked_range.h>
14#include <tbb/parallel_for.h>
15#include <tbb/parallel_for_each.h>
16#include <tbb/task_group.h>
17
18PXR_NAMESPACE_OPEN_SCOPE
19
24template <typename Fn>
25void
26WorkImpl_ParallelForN(size_t n, Fn &&callback, size_t grainSize)
27{
28 class Work_ParallelForN_TBB
29 {
30 public:
31 Work_ParallelForN_TBB(Fn &fn) : _fn(fn) { }
32
33 void operator()(const tbb::blocked_range<size_t> &r) const {
34 // Note that we std::forward _fn using Fn in order get the
35 // right operator().
36 // We maintain the right type in this way:
37 // If Fn is T&, then reference collapsing gives us T& for _fn
38 // If Fn is T, then std::forward correctly gives us T&& for _fn
39 std::forward<Fn>(_fn)(r.begin(), r.end());
40 }
41
42 private:
43 Fn &_fn;
44 };
45
46 // In most cases we do not want to inherit cancellation state from the
47 // parent context, so we create an isolated task group context.
48 tbb::task_group_context ctx(tbb::task_group_context::isolated);
49 tbb::parallel_for(tbb::blocked_range<size_t>(0,n,grainSize),
50 Work_ParallelForN_TBB(callback),
51 ctx);
52}
53
56template <typename InputIterator, typename Fn>
57inline void
58WorkImpl_ParallelForEach(
59 InputIterator first, InputIterator last, Fn &&fn)
60{
61 tbb::task_group_context ctx(tbb::task_group_context::isolated);
62 tbb::parallel_for_each(first, last, std::forward<Fn>(fn), ctx);
63}
64
65PXR_NAMESPACE_CLOSE_SCOPE
66
67#endif // PXR_BASE_WORK_TBB_LOOPS_H