atomic.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // ======================================================================== //
  2. // Copyright 2009-2017 Intel Corporation //
  3. // //
  4. // Licensed under the Apache License, Version 2.0 (the "License"); //
  5. // you may not use this file except in compliance with the License. //
  6. // You may obtain a copy of the License at //
  7. // //
  8. // http://www.apache.org/licenses/LICENSE-2.0 //
  9. // //
  10. // Unless required by applicable law or agreed to in writing, software //
  11. // distributed under the License is distributed on an "AS IS" BASIS, //
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
  13. // See the License for the specific language governing permissions and //
  14. // limitations under the License. //
  15. // ======================================================================== //
  16. #pragma once
  17. #include <atomic>
  18. #include "intrinsics.h"
  19. namespace embree
  20. {
  21. /* compiler memory barriers */
  22. #if defined(__INTEL_COMPILER)
  23. //#define __memory_barrier() __memory_barrier()
  24. #elif defined(__GNUC__) || defined(__clang__)
  25. # define __memory_barrier() asm volatile("" ::: "memory")
  26. #elif defined(_MSC_VER)
  27. # define __memory_barrier() _ReadWriteBarrier()
  28. #endif
  29. template <typename T>
  30. struct atomic : public std::atomic<T>
  31. {
  32. atomic () {}
  33. atomic (const T& a)
  34. : std::atomic<T>(a) {}
  35. atomic (const atomic<T>& a) {
  36. this->store(a.load());
  37. }
  38. atomic& operator=(const atomic<T>& other) {
  39. this->store(other.load());
  40. return *this;
  41. }
  42. };
  43. template<typename T>
  44. __forceinline void atomic_min(std::atomic<T>& aref, const T& bref)
  45. {
  46. const T b = bref.load();
  47. while (true) {
  48. T a = aref.load();
  49. if (a <= b) break;
  50. if (aref.compare_exchange_strong(a,b)) break;
  51. }
  52. }
  53. template<typename T>
  54. __forceinline void atomic_max(std::atomic<T>& aref, const T& bref)
  55. {
  56. const T b = bref.load();
  57. while (true) {
  58. T a = aref.load();
  59. if (a >= b) break;
  60. if (aref.compare_exchange_strong(a,b)) break;
  61. }
  62. }
  63. }