safe_refcount.hpp 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. /**************************************************************************/
  2. /* safe_refcount.hpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #pragma once
  31. #if !defined(NO_THREADS)
  32. #include <atomic>
  33. #include <type_traits>
  34. namespace godot {
  35. // Design goals for these classes:
  36. // - No automatic conversions or arithmetic operators,
  37. // to keep explicit the use of atomics everywhere.
  38. // - Using acquire-release semantics, even to set the first value.
  39. // The first value may be set relaxedly in many cases, but adding the distinction
  40. // between relaxed and unrelaxed operation to the interface would make it needlessly
  41. // flexible. There's negligible waste in having release semantics for the initial
  42. // value and, as an important benefit, you can be sure the value is properly synchronized
  43. // even with threads that are already running.
  44. // These are used in very specific areas of the engine where it's critical that these guarantees are held
  45. #define SAFE_NUMERIC_TYPE_PUN_GUARANTEES(m_type) \
  46. static_assert(sizeof(SafeNumeric<m_type>) == sizeof(m_type)); \
  47. static_assert(alignof(SafeNumeric<m_type>) == alignof(m_type)); \
  48. static_assert(std::is_trivially_destructible_v<std::atomic<m_type>>);
  49. #define SAFE_FLAG_TYPE_PUN_GUARANTEES \
  50. static_assert(sizeof(SafeFlag) == sizeof(bool)); \
  51. static_assert(alignof(SafeFlag) == alignof(bool));
  52. template <typename T>
  53. class SafeNumeric {
  54. std::atomic<T> value;
  55. static_assert(std::atomic<T>::is_always_lock_free);
  56. public:
  57. _ALWAYS_INLINE_ void set(T p_value) {
  58. value.store(p_value, std::memory_order_release);
  59. }
  60. _ALWAYS_INLINE_ T get() const {
  61. return value.load(std::memory_order_acquire);
  62. }
  63. _ALWAYS_INLINE_ T increment() {
  64. return value.fetch_add(1, std::memory_order_acq_rel) + 1;
  65. }
  66. // Returns the original value instead of the new one
  67. _ALWAYS_INLINE_ T postincrement() {
  68. return value.fetch_add(1, std::memory_order_acq_rel);
  69. }
  70. _ALWAYS_INLINE_ T decrement() {
  71. return value.fetch_sub(1, std::memory_order_acq_rel) - 1;
  72. }
  73. // Returns the original value instead of the new one
  74. _ALWAYS_INLINE_ T postdecrement() {
  75. return value.fetch_sub(1, std::memory_order_acq_rel);
  76. }
  77. _ALWAYS_INLINE_ T add(T p_value) {
  78. return value.fetch_add(p_value, std::memory_order_acq_rel) + p_value;
  79. }
  80. // Returns the original value instead of the new one
  81. _ALWAYS_INLINE_ T postadd(T p_value) {
  82. return value.fetch_add(p_value, std::memory_order_acq_rel);
  83. }
  84. _ALWAYS_INLINE_ T sub(T p_value) {
  85. return value.fetch_sub(p_value, std::memory_order_acq_rel) - p_value;
  86. }
  87. _ALWAYS_INLINE_ T bit_or(T p_value) {
  88. return value.fetch_or(p_value, std::memory_order_acq_rel);
  89. }
  90. _ALWAYS_INLINE_ T bit_and(T p_value) {
  91. return value.fetch_and(p_value, std::memory_order_acq_rel);
  92. }
  93. _ALWAYS_INLINE_ T bit_xor(T p_value) {
  94. return value.fetch_xor(p_value, std::memory_order_acq_rel);
  95. }
  96. // Returns the original value instead of the new one
  97. _ALWAYS_INLINE_ T postsub(T p_value) {
  98. return value.fetch_sub(p_value, std::memory_order_acq_rel);
  99. }
  100. _ALWAYS_INLINE_ T exchange_if_greater(T p_value) {
  101. while (true) {
  102. T tmp = value.load(std::memory_order_acquire);
  103. if (tmp >= p_value) {
  104. return tmp; // already greater, or equal
  105. }
  106. if (value.compare_exchange_weak(tmp, p_value, std::memory_order_acq_rel)) {
  107. return p_value;
  108. }
  109. }
  110. }
  111. _ALWAYS_INLINE_ T conditional_increment() {
  112. while (true) {
  113. T c = value.load(std::memory_order_acquire);
  114. if (c == 0) {
  115. return 0;
  116. }
  117. if (value.compare_exchange_weak(c, c + 1, std::memory_order_acq_rel)) {
  118. return c + 1;
  119. }
  120. }
  121. }
  122. _ALWAYS_INLINE_ explicit SafeNumeric(T p_value = static_cast<T>(0)) {
  123. set(p_value);
  124. }
  125. };
  126. class SafeFlag {
  127. std::atomic_bool flag;
  128. static_assert(std::atomic_bool::is_always_lock_free);
  129. public:
  130. _ALWAYS_INLINE_ bool is_set() const {
  131. return flag.load(std::memory_order_acquire);
  132. }
  133. _ALWAYS_INLINE_ void set() {
  134. flag.store(true, std::memory_order_release);
  135. }
  136. _ALWAYS_INLINE_ void clear() {
  137. flag.store(false, std::memory_order_release);
  138. }
  139. _ALWAYS_INLINE_ void set_to(bool p_value) {
  140. flag.store(p_value, std::memory_order_release);
  141. }
  142. _ALWAYS_INLINE_ explicit SafeFlag(bool p_value = false) {
  143. set_to(p_value);
  144. }
  145. };
  146. class SafeRefCount {
  147. SafeNumeric<uint32_t> count;
  148. #ifdef DEV_ENABLED
  149. _ALWAYS_INLINE_ void _check_unref_safety() {
  150. // This won't catch every misuse, but it's better than nothing.
  151. CRASH_COND_MSG(count.get() == 0,
  152. "Trying to unreference a SafeRefCount which is already zero is wrong and a symptom of it being misused.\n"
  153. "Upon a SafeRefCount reaching zero any object whose lifetime is tied to it, as well as the ref count itself, must be destroyed.\n"
  154. "Moreover, to guarantee that, no multiple threads should be racing to do the final unreferencing to zero.");
  155. }
  156. #endif
  157. public:
  158. _ALWAYS_INLINE_ bool ref() { // true on success
  159. return count.conditional_increment() != 0;
  160. }
  161. _ALWAYS_INLINE_ uint32_t refval() { // none-zero on success
  162. return count.conditional_increment();
  163. }
  164. _ALWAYS_INLINE_ bool unref() { // true if must be disposed of
  165. #ifdef DEV_ENABLED
  166. _check_unref_safety();
  167. #endif
  168. return count.decrement() == 0;
  169. }
  170. _ALWAYS_INLINE_ uint32_t unrefval() { // 0 if must be disposed of
  171. #ifdef DEV_ENABLED
  172. _check_unref_safety();
  173. #endif
  174. return count.decrement();
  175. }
  176. _ALWAYS_INLINE_ uint32_t get() const {
  177. return count.get();
  178. }
  179. _ALWAYS_INLINE_ void init(uint32_t p_value = 1) {
  180. count.set(p_value);
  181. }
  182. };
  183. } // namespace godot
  184. #endif // !defined(NO_THREADS)