add usd-21-11-win64_py39

This commit is contained in:
Sébastien Albert committed 2021-12-07 17:43:55 +01:00
1 parent 41d23e71ba
commit ba5e1f7e67
15684 files changed
+3069957

No files matched your search

+47
View File
@@ -0,0 +1,47 @@
//
// Copyright 2017 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_WORK_API_H
#define PXR_BASE_WORK_API_H
#include "pxr/base/arch/export.h"
#if defined(PXR_STATIC)
# define WORK_API
# define WORK_API_TEMPLATE_CLASS(...)
# define WORK_API_TEMPLATE_STRUCT(...)
# define WORK_LOCAL
#else
# if defined(WORK_EXPORTS)
# define WORK_API ARCH_EXPORT
# define WORK_API_TEMPLATE_CLASS(...) ARCH_EXPORT_TEMPLATE(class, __VA_ARGS__)
# define WORK_API_TEMPLATE_STRUCT(...) ARCH_EXPORT_TEMPLATE(struct, __VA_ARGS__)
# else
# define WORK_API ARCH_IMPORT
# define WORK_API_TEMPLATE_CLASS(...) ARCH_IMPORT_TEMPLATE(class, __VA_ARGS__)
# define WORK_API_TEMPLATE_STRUCT(...) ARCH_IMPORT_TEMPLATE(struct, __VA_ARGS__)
# endif
# define WORK_LOCAL ARCH_HIDDEN
#endif
#endif
+77
View File
@@ -0,0 +1,77 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_WORK_DETACHED_TASK_H
#define PXR_BASE_WORK_DETACHED_TASK_H
/// \file work/detachedTask.h
#include "pxr/pxr.h"
#include "pxr/base/tf/errorMark.h"
#include "pxr/base/work/api.h"
#include "pxr/base/work/dispatcher.h"
#include <type_traits>
#include <utility>
PXR_NAMESPACE_OPEN_SCOPE
template <class Fn>
struct Work_DetachedTask
{
explicit Work_DetachedTask(Fn &&fn) : _fn(std::move(fn)) {}
explicit Work_DetachedTask(Fn const &fn) : _fn(fn) {}
void operator()() {
TfErrorMark m;
_fn();
m.Clear();
}
private:
Fn _fn;
};
WORK_API
WorkDispatcher &Work_GetDetachedDispatcher();
WORK_API
void Work_EnsureDetachedTaskProgress();
/// Invoke \p fn asynchronously, discard any errors it produces, and provide
/// no way to wait for it to complete.
template <class Fn>
void WorkRunDetachedTask(Fn &&fn)
{
using FnType = typename std::remove_reference<Fn>::type;
Work_DetachedTask<FnType> task(std::forward<Fn>(fn));
if (WorkHasConcurrency()) {
Work_GetDetachedDispatcher().Run(std::move(task));
Work_EnsureDetachedTaskProgress();
}
else {
task();
}
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_WORK_DETACHED_TASK_H
+183
View File
@@ -0,0 +1,183 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_WORK_DISPATCHER_H
#define PXR_BASE_WORK_DISPATCHER_H
/// \file work/dispatcher.h
#include "pxr/pxr.h"
#include "pxr/base/work/threadLimits.h"
#include "pxr/base/work/api.h"
#include "pxr/base/tf/errorMark.h"
#include "pxr/base/tf/errorTransport.h"
#include <tbb/concurrent_vector.h>
#include <tbb/task.h>
#include <functional>
#include <type_traits>
#include <utility>
PXR_NAMESPACE_OPEN_SCOPE
/// \class WorkDispatcher
///
/// A work dispatcher runs concurrent tasks. The dispatcher supports adding
/// new tasks from within running tasks. This suits problems that exhibit
/// hierarchical structured parallelism: tasks that discover additional tasks
/// during their execution.
///
/// Typical use is to create a dispatcher and invoke Run() to begin doing
/// work, then Wait() for the work to complete. Tasks may invoke Run() during
/// their execution as they discover additional tasks to perform.
///
/// For example,
///
/// \code
/// WorkDispatcher dispatcher;
/// for (i = 0; i != N; ++i) {
/// dispatcher.Run(DoSomeWork, workItem[i]);
/// }
/// dispatcher.Wait();
/// \endcode
///
/// Calls to Run() and Cancel() may be made concurrently. However, once Wait()
/// is called, calls to Run() and Cancel() must only be made by tasks already
/// added by Run(). Additionally, Wait() must never be called by a task added by
/// Run(), since that task could never complete.
///
class WorkDispatcher
{
public:
/// Construct a new dispatcher.
WORK_API WorkDispatcher();
/// Wait() for any pending tasks to complete, then destroy the dispatcher.
WORK_API ~WorkDispatcher();
WorkDispatcher(WorkDispatcher const &) = delete;
WorkDispatcher &operator=(WorkDispatcher const &) = delete;
#ifdef doxygen
/// Add work for the dispatcher to run.
///
/// Before a call to Wait() is made it is safe for any client to invoke
/// Run(). Once Wait() is invoked, it is \b only safe to invoke Run() from
/// within the execution of tasks already added via Run().
///
/// This function does not block, in general. It may block if concurrency
/// is limited to 1. The added work may be not yet started, may be started
/// but not completed, or may be completed upon return. No guarantee is
/// made.
template <class Callable, class A1, class A2, ... class AN>
void Run(Callable &&c, A1 &&a1, A2 &&a2, ... AN &&aN);
#else // doxygen
template <class Callable>
inline void Run(Callable &&c) {
_rootTask->spawn(_MakeInvokerTask(std::forward<Callable>(c)));
}
template <class Callable, class A0, class ... Args>
inline void Run(Callable &&c, A0 &&a0, Args&&... args) {
Run(std::bind(std::forward<Callable>(c),
std::forward<A0>(a0),
std::forward<Args>(args)...));
}
#endif // doxygen
/// Block until the work started by Run() completes.
WORK_API void Wait();
/// Cancel remaining work and return immediately.
///
/// Calling this function affects task that are being run directly
/// by this dispatcher. If any of these tasks are using their own
/// dispatchers to run tasks, these dispatchers will not be affected
/// and these tasks will run to completion, unless they are also
/// explicitly cancelled.
///
/// This call does not block. Call Wait() after Cancel() to wait for
/// pending tasks to complete.
WORK_API void Cancel();
private:
typedef tbb::concurrent_vector<TfErrorTransport> _ErrorTransports;
// Function invoker helper that wraps the invocation with an ErrorMark so we
// can transmit errors that occur back to the thread that Wait() s for tasks
// to complete.
template <class Fn>
struct _InvokerTask : public tbb::task {
explicit _InvokerTask(Fn &&fn, _ErrorTransports *err)
: _fn(std::move(fn)), _errors(err) {}
explicit _InvokerTask(Fn const &fn, _ErrorTransports *err)
: _fn(fn), _errors(err) {}
virtual tbb::task* execute() {
TfErrorMark m;
_fn();
if (!m.IsClean())
WorkDispatcher::_TransportErrors(m, _errors);
return NULL;
}
private:
Fn _fn;
_ErrorTransports *_errors;
};
// Make an _InvokerTask instance, letting the function template deduce Fn.
template <class Fn>
_InvokerTask<typename std::remove_reference<Fn>::type>&
_MakeInvokerTask(Fn &&fn) {
return *new( _rootTask->allocate_additional_child_of(*_rootTask) )
_InvokerTask<typename std::remove_reference<Fn>::type>(
std::forward<Fn>(fn), &_errors);
}
// Helper function that removes errors from \p m and stores them in a new
// entry in \p errors.
WORK_API static void
_TransportErrors(const TfErrorMark &m, _ErrorTransports *errors);
// Task group context and associated root task that allows us to cancel
// tasks invoked directly by this dispatcher.
tbb::task_group_context _context;
tbb::empty_task* _rootTask;
// The error transports we use to transmit errors in other threads back to
// this thread.
_ErrorTransports _errors;
};
///////////////////////////////////////////////////////////////////////////////
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_WORK_DISPATCHER_H
+158
View File
@@ -0,0 +1,158 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_WORK_LOOPS_H
#define PXR_BASE_WORK_LOOPS_H
/// \file work/loops.h
#include "pxr/pxr.h"
#include "pxr/base/work/threadLimits.h"
#include "pxr/base/work/api.h"
#include <tbb/blocked_range.h>
#include <tbb/parallel_for.h>
#include <tbb/parallel_for_each.h>
#include <tbb/task.h>
PXR_NAMESPACE_OPEN_SCOPE
///////////////////////////////////////////////////////////////////////////////
///
/// WorkSerialForN(size_t n, CallbackType callback)
///
/// A serial version of WorkParallelForN as a drop in replacement to
/// selectively turn off multithreading for a single parallel loop for easier
/// debugging.
///
/// Callback must be of the form:
///
/// void LoopCallback(size_t begin, size_t end);
///
template<typename Fn>
void
WorkSerialForN(size_t n, Fn &&fn)
{
std::forward<Fn>(fn)(0, n);
}
///////////////////////////////////////////////////////////////////////////////
///
/// WorkParallelForN(size_t n, CallbackType callback, size_t grainSize = 1)
///
/// Runs \p callback in parallel over the range 0 to n.
///
/// Callback must be of the form:
///
/// void LoopCallback(size_t begin, size_t end);
///
/// grainSize specifies a minimum amount of work to be done per-thread. There
/// is overhead to launching a thread (or task) and a typical guideline is that
/// you want to have at least 10,000 instructions to count for the overhead of
/// launching a thread.
///
template <typename Fn>
void
WorkParallelForN(size_t n, Fn &&callback, size_t grainSize)
{
if (n == 0)
return;
// Don't bother with parallel_for, if concurrency is limited to 1.
if (WorkHasConcurrency()) {
class Work_ParallelForN_TBB
{
public:
Work_ParallelForN_TBB(Fn &fn) : _fn(fn) { }
void operator()(const tbb::blocked_range<size_t> &r) const {
// Note that we std::forward _fn using Fn in order get the
// right operator().
// We maintain the right type in this way:
// If Fn is T&, then reference collapsing gives us T& for _fn
// If Fn is T, then std::forward correctly gives us T&& for _fn
std::forward<Fn>(_fn)(r.begin(), r.end());
}
private:
Fn &_fn;
};
// In most cases we do not want to inherit cancellation state from the
// parent context, so we create an isolated task group context.
tbb::task_group_context ctx(tbb::task_group_context::isolated);
tbb::parallel_for(tbb::blocked_range<size_t>(0,n,grainSize),
Work_ParallelForN_TBB(callback),
ctx);
} else {
// If concurrency is limited to 1, execute serially.
WorkSerialForN(n, std::forward<Fn>(callback));
}
}
///////////////////////////////////////////////////////////////////////////////
///
/// WorkParallelForN(size_t n, CallbackType callback, size_t grainSize = 1)
///
/// Runs \p callback in parallel over the range 0 to n.
///
/// Callback must be of the form:
///
/// void LoopCallback(size_t begin, size_t end);
///
///
template <typename Fn>
void
WorkParallelForN(size_t n, Fn &&callback)
{
WorkParallelForN(n, std::forward<Fn>(callback), 1);
}
///////////////////////////////////////////////////////////////////////////////
///
/// WorkParallelForEach(Iterator first, Iterator last, CallbackType callback)
///
/// Callback must be of the form:
///
/// void LoopCallback(T elem);
///
/// where the type T is deduced from the type of the InputIterator template
/// argument.
///
///
///
template <typename InputIterator, typename Fn>
inline void
WorkParallelForEach(
InputIterator first, InputIterator last, Fn &&fn)
{
tbb::task_group_context ctx(tbb::task_group_context::isolated);
tbb::parallel_for_each(first, last, std::forward<Fn>(fn), ctx);
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_WORK_LOOPS_H
+168
View File
@@ -0,0 +1,168 @@
//
// Copyright 2018 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_WORK_REDUCE_H
#define PXR_BASE_WORK_REDUCE_H
/// \file work/reduce.h
#include "pxr/pxr.h"
#include "pxr/base/work/threadLimits.h"
#include "pxr/base/work/api.h"
#include <tbb/blocked_range.h>
#include <tbb/parallel_reduce.h>
#include <tbb/task.h>
PXR_NAMESPACE_OPEN_SCOPE
///////////////////////////////////////////////////////////////////////////////
///
/// Recursively splits the range [0, \p n) into subranges, which are then
/// reduced by invoking \p loopCallback in parallel. Each invocation of
/// \p loopCallback returns a single value that is the result of joining the
/// elements in the respective subrange. These values are then further joined
/// using the binary operator \p reductionCallback, until only a single value
/// remains. This single value is then the result of joining all elements over
/// the entire range [0, \p n).
///
/// The \p loopCallback must be of the form:
///
/// V LoopCallback(size_t begin, size_t end, const V &identity);
///
/// The \p reductionCallback must be of the form:
///
/// V ReductionCallback(const V &lhs, const V &rhs);
///
/// For example, the following code reduces an array of mesh points into a
/// single bounding box:
///
/// ```{.cpp}
///
/// // Get the mesh points from which we are going to generate the bounding box.
/// const std::vector<Vector3> &points = GetMeshPoints();
///
/// // Generate the bounding box by parallel reducing the points.
/// BoundingBox bbox = WorkParallelReduceN(
/// BoundingBox(),
/// points.size(),
/// [&points](size_t b, size_t e, const BoundingBox &identity){
/// BoundingBox bbox(identity);
///
/// // Insert each point in this subrange into the local bounding box.
/// for (size_t i = b; i != e; ++i) {
/// bbox.InsertPoint(points[i]);
/// }
///
/// // Return the local bounding box, which now encapsulates all the
/// // points in this subrange.
/// return bbox;
/// },
/// [](const BoundingBox &lhs, const BoundingBox &rhs){
/// // Join two bounding boxes into a single bounding box. The
/// // algorithm will apply this reduction step recursively until there
/// // is only a single bounding box left.
/// BoundingBox bbox(lhs);
/// bbox.UnionWith(rhs);
/// return bbox;
/// }
/// );
///
/// ```
///
/// \p grainSize specifies a minimum amount of work to be done per-thread.
/// There is overhead to launching a task and a typical guideline is that
/// you want to have at least 10,000 instructions to count for the overhead of
/// launching that task.
///
template <typename Fn, typename Rn, typename V>
V
WorkParallelReduceN(
const V &identity,
size_t n,
Fn &&loopCallback,
Rn &&reductionCallback,
size_t grainSize)
{
if (n == 0)
return identity;
// Don't bother with parallel_reduce, if concurrency is limited to 1.
if (WorkHasConcurrency()) {
class Work_Body_TBB
{
public:
Work_Body_TBB(Fn &fn) : _fn(fn) { }
V operator()(
const tbb::blocked_range<size_t> &r,
const V &value) const {
// Note that we std::forward _fn using Fn in order get the
// right operator().
// We maintain the right type in this way:
// If Fn is T&, then reference collapsing gives us T& for _fn
// If Fn is T, then std::forward correctly gives us T&& for _fn
return std::forward<Fn>(_fn)(r.begin(), r.end(), value);
}
private:
Fn &_fn;
};
// In most cases we do not want to inherit cancellation state from the
// parent context, so we create an isolated task group context.
tbb::task_group_context ctx(tbb::task_group_context::isolated);
return tbb::parallel_reduce(tbb::blocked_range<size_t>(0,n,grainSize),
identity,
Work_Body_TBB(loopCallback),
std::forward<Rn>(reductionCallback),
tbb::auto_partitioner(),
ctx);
}
// If concurrency is limited to 1, execute serially.
return std::forward<Fn>(loopCallback)(0, n, identity);
}
///////////////////////////////////////////////////////////////////////////////
///
/// \overload
///
/// This overload does not accept a grain size parameter and instead attempts
/// to automatically deduce a grain size that is optimal for the current
/// resource utilization and provided workload.
///
template <typename Fn, typename Rn, typename V>
V
WorkParallelReduceN(
const V &identity,
size_t n,
Fn &&loopCallback,
Rn &&reductionCallback)
{
return WorkParallelReduceN(identity, n, loopCallback, reductionCallback, 1);
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_WORK_REDUCE_H
+134
View File
@@ -0,0 +1,134 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_WORK_SINGULAR_TASK_H
#define PXR_BASE_WORK_SINGULAR_TASK_H
/// \file work/singularTask.h
#include "pxr/pxr.h"
#include <atomic>
#include <functional>
#include <type_traits>
PXR_NAMESPACE_OPEN_SCOPE
class WorkDispatcher;
/// \class WorkSingularTask
///
/// A WorkSingularTask runs a task in a WorkDispatcher, but never concurrently
/// with itself. That is, the function provided to the WorkSingularTask runs
/// concurrently with other tasks in the WorkDispatcher, but never with another
/// invocation of itself.
///
/// This is useful if there is single-threaded work to do that can be overlapped
/// with other parallel tasks in a dispatcher. For example, a
/// multiple-producer, single-consumer problem can be tackled this way. Run the
/// producer tasks as usual in a WorkDispatcher and create a WorkSingularTask
/// for the consumer. When a producer task has generated a result to consume,
/// it invokes Wake() on the consumer task. This ensures that the consumer runs
/// only when there are results to consume, and it lets the consumer operate
/// single-threaded. For example, the consumer could populate stl containers
/// without locking.
///
class WorkSingularTask
{
public:
WorkSingularTask(WorkSingularTask const &) = delete;
WorkSingularTask &operator=(WorkSingularTask const &) = delete;
#ifdef doxygen
/// Create a singular task to be run in \p dispatcher. Callers must ensure
/// that \p dispatcher lives at least as long as this WorkSingularTask.
///
/// A singular task is one that will not run concurrently with itself. See
/// the WorkSingularTask doc for more details.
///
/// After constructing a WorkSingularTask, call Wake() to ensure that the
/// task runs at least once.
template <class Callable, class A1, class A2, ... class AN>
WorkSingularTask(WorkDispatcher &dispatcher,
Callable &&c, A1 &&a1, A2 &&a2, ... AN &&aN);
#else // doxygen
template <class Callable, class... Args>
WorkSingularTask(WorkDispatcher &d, Callable &&c, Args&&... args)
: _waker(_MakeWaker(d, std::bind(std::forward<Callable>(c),
std::forward<Args>(args)...)))
, _count(0) {}
#endif // doxygen
/// Ensure that this task runs at least once after this call. The task is
/// not guaranteed to run as many times as Wake() is invoked, only that it
/// run at least once after a call to Wake().
inline void Wake() {
if (++_count == 1)
_waker(_count);
}
private:
template <class Dispatcher, class Fn>
struct _Waker {
explicit _Waker(Dispatcher &d, Fn &&fn)
: _dispatcher(d), _fn(std::move(fn)) {}
void operator()(std::atomic_size_t &count) const {
_dispatcher.Run(
[this, &count]() {
// We read the current refCount into oldCount, then we
// invoke the task function. Finally we try to CAS the
// refCount to zero. If we fail, it means some other
// clients have invoked Wake() in the meantime. In that
// case we go again to ensure the task can do whatever it
// was awakened to do. Once we successfully take the count
// to zero, we stop.
size_t old = count;
do { _fn(); } while (
!count.compare_exchange_strong(old, 0));
});
}
Dispatcher &_dispatcher;
Fn _fn;
};
template <class Dispatcher, class Fn>
static std::function<void (std::atomic_size_t &)>
_MakeWaker(Dispatcher &d, Fn &&fn) {
return std::function<void (std::atomic_size_t &)>(
_Waker<Dispatcher, typename std::decay<Fn>::type>(
d, std::forward<Fn>(fn)));
}
std::function<void (std::atomic_size_t &)> _waker;
std::atomic_size_t _count;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_WORK_SINGULAR_TASK_H
+103
View File
@@ -0,0 +1,103 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_WORK_THREAD_LIMITS_H
#define PXR_BASE_WORK_THREAD_LIMITS_H
#include "pxr/pxr.h"
#include "pxr/base/work/api.h"
PXR_NAMESPACE_OPEN_SCOPE
/// \file work/threadLimits.h
/// Return the current concurrency limit, always >= 1.
///
/// This value is determined by the underlying concurrency subsystem. It may
/// have been set by a third party, by a call to Work API below, or by Work
/// itself if the PXR_WORK_THREAD_LIMIT env setting was set. If the
/// PXR_WORK_THREAD_LIMIT env setting has been explicitly set to a non-zero
/// value, Work will attempt to configure the underlying concurrency subsystem
/// to use the specified limit and will ignore concurrency limits set via the
/// API calls below.
///
/// Note that this can return a value larger than
/// WorkGetPhysicalConcurrencyLimit() if WorkSetConcurrencyLimit() was called
/// with such a value, or if PXR_WORK_THREAD_LIMIT was set with such a value.
///
WORK_API unsigned WorkGetConcurrencyLimit();
/// Return true if WorkGetPhysicalConcurrencyLimit() returns a number greater
/// than 1 and PXR_WORK_THREAD_LIMIT was not set in an attempt to limit the
/// process to a single thread, false otherwise.
///
WORK_API bool WorkHasConcurrency();
/// Return the number of physical execution cores available to the program.
/// This is either the number of physical cores on the machine or the number of
/// cores specified by the process's affinity mask, whichever is smaller.
///
WORK_API unsigned WorkGetPhysicalConcurrencyLimit();
/// Set the concurrency limit to \p n, if \p n is a non-zero value.
///
/// If \p n is zero, then do not change the current concurrency limit.
///
/// Note, calling this function with n > WorkGetPhysicalConcurrencyLimit() may
/// overtax the machine.
///
/// In general, very few places should call this function. Call it in places
/// where the number of allowed threads is dictated, for example, by a hosting
/// environment. Lower-level library code should never call this function.
///
WORK_API void WorkSetConcurrencyLimit(unsigned n);
/// Sanitize \p n as described below and set the concurrency limit accordingly.
/// This function is useful for interpreting command line arguments.
///
/// If \p n is zero, then do not change the current concurrency limit.
///
/// If \p n is a positive, non-zero value then call WorkSetConcurrencyLimit(n).
/// Note that calling this method with \p n greater than the value returned by
/// WorkGetPhysicalConcurrencyLimit() may overtax the machine.
///
/// If \p n is negative, then set the concurrency limit to all but abs(\p n)
/// cores. The number of cores is determined by the value returned by
/// WorkGetPhysicalConcurrencyLimit().
/// For example, if \p n is -2, then use all but two cores. If abs(\p n) is
/// greater than the number of physical cores, then call
/// WorkSetConcurrencyLimit(1), effectively disabling concurrency.
///
WORK_API void WorkSetConcurrencyLimitArgument(int n);
/// Set the concurrency limit to be the maximum recommended for the hardware
/// on which it's running. Equivalent to:
/// \code
/// WorkSetConcurrencyLimit(WorkGetPhysicalConcurrencyLimit()).
/// \endcode
///
WORK_API void WorkSetMaximumConcurrencyLimit();
PXR_NAMESPACE_CLOSE_SCOPE
#endif
+104
View File
@@ -0,0 +1,104 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_WORK_UTILS_H
#define PXR_BASE_WORK_UTILS_H
///\file work/utils.h
#include "pxr/pxr.h"
#include "pxr/base/work/api.h"
#include "pxr/base/work/detachedTask.h"
#include <utility>
PXR_NAMESPACE_OPEN_SCOPE
WORK_API
bool Work_ShouldSynchronizeAsyncDestroyCalls();
template <class T>
struct Work_AsyncMoveDestroyHelper {
void operator()() const { /* do nothing */ }
T obj;
};
// Helper for swap-based asynchronous destruction that synthesizes move
// construction and assignment using swap.
template <class T>
struct Work_AsyncSwapDestroyHelper {
Work_AsyncSwapDestroyHelper() = default;
Work_AsyncSwapDestroyHelper(Work_AsyncSwapDestroyHelper const&) = delete;
Work_AsyncSwapDestroyHelper& operator=(
Work_AsyncSwapDestroyHelper const&) = delete;
Work_AsyncSwapDestroyHelper(Work_AsyncSwapDestroyHelper &&other)
: obj()
{
using std::swap;
swap(obj, other.obj);
}
Work_AsyncSwapDestroyHelper& operator=(
Work_AsyncSwapDestroyHelper &&other)
{
using std::swap;
swap(obj, other.obj);
return *this;
}
void operator()() const { /* do nothing */ }
T obj;
};
/// Swap \p obj with a default-constructed T instance, return and arrange
/// for the swapped-out instance to be destroyed asynchronously. This means
/// that any code that obj's destructor might invoke must be safe to run both
/// concurrently with other code and at any point in the future. This might not
/// be true, for example, if obj's destructor might try to update some other
/// data structure that could be destroyed by the time obj's destruction occurs.
/// Be careful.
template <class T>
void WorkSwapDestroyAsync(T &obj)
{
using std::swap;
Work_AsyncSwapDestroyHelper<T> helper;
swap(helper.obj, obj);
if (!Work_ShouldSynchronizeAsyncDestroyCalls())
WorkRunDetachedTask(std::move(helper));
}
/// Like WorkSwapDestroyAsync() but instead, move from \p obj, leaving it
/// in a moved-from state instead of a default constructed state.
template <class T>
void WorkMoveDestroyAsync(T &obj)
{
Work_AsyncMoveDestroyHelper<T> helper { std::move(obj) };
if (!Work_ShouldSynchronizeAsyncDestroyCalls())
WorkRunDetachedTask(std::move(helper));
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_WORK_UTILS_H
@@ -0,0 +1,119 @@
//
// Copyright 2021 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_BASE_WORK_WITH_SCOPED_PARALLELISM_H
#define PXR_BASE_WORK_WITH_SCOPED_PARALLELISM_H
///\file work/withScopedParallelism.h
#include "pxr/pxr.h"
#include "pxr/base/work/api.h"
#include <tbb/task_arena.h>
#include <utility>
PXR_NAMESPACE_OPEN_SCOPE
/// Invoke \p fn, ensuring that all wait operations on concurrent constructs
/// invoked by the calling thread only take tasks created within the scope of \p
/// fn 's execution.
///
/// Ordinarily when a thread invokes a wait operation on a concurrent construct
/// (e.g. the explicit WorkDispatcher::Wait(), or the implicit wait in loops
/// like WorkParallelForEach()) it joins the pool of worker threads and executes
/// tasks to help complete the work. This is good, since the calling thread
/// does useful work instead of busy waiting or sleeping until the work has
/// completed. However, this can be problematic depending on the calling
/// context, and which tasks the waiting thread executes.
///
/// For example, consider the following example: a demand-populated resource
/// cache.
///
/// \code
/// ResourceHandle
/// GetResource(ResourceKey key) {
/// // Attempt to lookup/insert an entry for \p key. If we insert the
/// // element, then populate the resource.
/// ResourceAccessorAndLock accessor;
/// if (_resources.FindOrCreate(key, &accessor)) {
/// // No previous entry, so populate the resource.
/// WorkDispatcher wd;
/// wd.Run( /* resource population task 1 */);
/// wd.Run( /* resource population task 2 */);
/// wd.Run( /* resource population task 3 */);
/// WorkParallelForN( /* parallel population code */);
/// wd.Wait();
/// /* Store resource data. */
/// }
/// return *accessor.first;
/// }
/// \endcode
///
/// Here when a caller has requested the resource for \p key for the first time,
/// we do the work to populate the resource while holding a lock on that
/// resource entry in the cache. The problem is that when the calling thread
/// waits for work to complete, if it picks up tasks unrelated to this context
/// and those tasks attempt to call GetResource() with the same key, the process
/// will deadlock.
///
/// This can be fixed by using WorkWithScopedParallelism() to ensure that the
/// calling thread's wait operations only take tasks that were created during
/// the scope of the population work:
///
/// \code
/// ResourceHandle
/// GetResource(ResourceKey key) {
/// // Attempt to lookup/insert an entry for \p key. If we insert the
/// // element, then populate the resource.
/// ResourceAccessorAndLock accessor;
/// if (_resources.FindOrCreate(key, &accessor)) {
/// // No previous entry, so populate the resource.
/// WorkWithScopedParallelism([&accessor]() {
/// WorkDispatcher wd;
/// wd.Run( /* resource population task 1 */);
/// wd.Run( /* resource population task 2 */);
/// wd.Run( /* resource population task 3 */);
/// WorkParallelForN( /* parallel population code */);
/// }
/// /* Store resource data. */
/// }
/// return *accessor.first;
/// }
///
/// This limits parallelism by only a small degree. It's only the waiting
/// thread that restricts the tasks it can take to the protected scope: all
/// other worker threads continue unhindered.
///
template <class Fn>
void
WorkWithScopedParallelism(Fn &&fn)
{
tbb::this_task_arena::isolate(std::forward<Fn>(fn));
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_BASE_WORK_WITH_SCOPED_PARALLELISM_H