Atomics.h 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #pragma once
  5. JPH_SUPPRESS_WARNINGS_STD_BEGIN
  6. #include <atomic>
  7. JPH_SUPPRESS_WARNINGS_STD_END
  8. JPH_NAMESPACE_BEGIN
  9. // Things we're using from STL
  10. using std::atomic;
  11. using std::memory_order;
  12. using std::memory_order_relaxed;
  13. using std::memory_order_acquire;
  14. using std::memory_order_release;
  15. using std::memory_order_acq_rel;
  16. using std::memory_order_seq_cst;
  17. /// Atomically compute the min(ioAtomic, inValue) and store it in ioAtomic, returns true if value was updated
  18. template <class T>
  19. bool AtomicMin(atomic<T> &ioAtomic, const T inValue, const memory_order inMemoryOrder = memory_order_seq_cst)
  20. {
  21. T cur_value = ioAtomic.load(memory_order_relaxed);
  22. while (cur_value > inValue)
  23. if (ioAtomic.compare_exchange_weak(cur_value, inValue, inMemoryOrder))
  24. return true;
  25. return false;
  26. }
  27. /// Atomically compute the max(ioAtomic, inValue) and store it in ioAtomic, returns true if value was updated
  28. template <class T>
  29. bool AtomicMax(atomic<T> &ioAtomic, const T inValue, const memory_order inMemoryOrder = memory_order_seq_cst)
  30. {
  31. T cur_value = ioAtomic.load(memory_order_relaxed);
  32. while (cur_value < inValue)
  33. if (ioAtomic.compare_exchange_weak(cur_value, inValue, inMemoryOrder))
  34. return true;
  35. return false;
  36. }
  37. JPH_NAMESPACE_END