safe_refcount.h 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. /**************************************************************************/
  2. /* safe_refcount.h */
  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. #ifndef SAFE_REFCOUNT_H
  31. #define SAFE_REFCOUNT_H
  32. #include "core/typedefs.h"
  33. #ifdef DEV_ENABLED
  34. #include "core/error/error_macros.h"
  35. #endif
  36. #include <atomic>
  37. #include <type_traits>
  38. // Design goals for these classes:
  39. // - No automatic conversions or arithmetic operators,
  40. // to keep explicit the use of atomics everywhere.
  41. // - Using acquire-release semantics, even to set the first value.
  42. // The first value may be set relaxedly in many cases, but adding the distinction
  43. // between relaxed and unrelaxed operation to the interface would make it needlessly
  44. // flexible. There's negligible waste in having release semantics for the initial
  45. // value and, as an important benefit, you can be sure the value is properly synchronized
  46. // even with threads that are already running.
  47. // These are used in very specific areas of the engine where it's critical that these guarantees are held
  48. #define SAFE_NUMERIC_TYPE_PUN_GUARANTEES(m_type) \
  49. static_assert(sizeof(SafeNumeric<m_type>) == sizeof(m_type)); \
  50. static_assert(alignof(SafeNumeric<m_type>) == alignof(m_type)); \
  51. static_assert(std::is_trivially_destructible<std::atomic<m_type>>::value);
  52. #define SAFE_FLAG_TYPE_PUN_GUARANTEES \
  53. static_assert(sizeof(SafeFlag) == sizeof(bool)); \
  54. static_assert(alignof(SafeFlag) == alignof(bool));
  55. template <class T>
  56. class SafeNumeric {
  57. std::atomic<T> value;
  58. static_assert(std::atomic<T>::is_always_lock_free);
  59. public:
  60. _ALWAYS_INLINE_ void set(T p_value) {
  61. value.store(p_value, std::memory_order_release);
  62. }
  63. _ALWAYS_INLINE_ T get() const {
  64. return value.load(std::memory_order_acquire);
  65. }
  66. _ALWAYS_INLINE_ T increment() {
  67. return value.fetch_add(1, std::memory_order_acq_rel) + 1;
  68. }
  69. // Returns the original value instead of the new one
  70. _ALWAYS_INLINE_ T postincrement() {
  71. return value.fetch_add(1, std::memory_order_acq_rel);
  72. }
  73. _ALWAYS_INLINE_ T decrement() {
  74. return value.fetch_sub(1, std::memory_order_acq_rel) - 1;
  75. }
  76. // Returns the original value instead of the new one
  77. _ALWAYS_INLINE_ T postdecrement() {
  78. return value.fetch_sub(1, std::memory_order_acq_rel);
  79. }
  80. _ALWAYS_INLINE_ T add(T p_value) {
  81. return value.fetch_add(p_value, std::memory_order_acq_rel) + p_value;
  82. }
  83. // Returns the original value instead of the new one
  84. _ALWAYS_INLINE_ T postadd(T p_value) {
  85. return value.fetch_add(p_value, std::memory_order_acq_rel);
  86. }
  87. _ALWAYS_INLINE_ T sub(T p_value) {
  88. return value.fetch_sub(p_value, std::memory_order_acq_rel) - p_value;
  89. }
  90. _ALWAYS_INLINE_ T bit_or(T p_value) {
  91. return value.fetch_or(p_value, std::memory_order_acq_rel);
  92. }
  93. _ALWAYS_INLINE_ T bit_and(T p_value) {
  94. return value.fetch_and(p_value, std::memory_order_acq_rel);
  95. }
  96. _ALWAYS_INLINE_ T bit_xor(T p_value) {
  97. return value.fetch_xor(p_value, std::memory_order_acq_rel);
  98. }
  99. // Returns the original value instead of the new one
  100. _ALWAYS_INLINE_ T postsub(T p_value) {
  101. return value.fetch_sub(p_value, std::memory_order_acq_rel);
  102. }
  103. _ALWAYS_INLINE_ T exchange_if_greater(T p_value) {
  104. while (true) {
  105. T tmp = value.load(std::memory_order_acquire);
  106. if (tmp >= p_value) {
  107. return tmp; // already greater, or equal
  108. }
  109. if (value.compare_exchange_weak(tmp, p_value, std::memory_order_acq_rel)) {
  110. return p_value;
  111. }
  112. }
  113. }
  114. _ALWAYS_INLINE_ T conditional_increment() {
  115. while (true) {
  116. T c = value.load(std::memory_order_acquire);
  117. if (c == 0) {
  118. return 0;
  119. }
  120. if (value.compare_exchange_weak(c, c + 1, std::memory_order_acq_rel)) {
  121. return c + 1;
  122. }
  123. }
  124. }
  125. _ALWAYS_INLINE_ explicit SafeNumeric(T p_value = static_cast<T>(0)) {
  126. set(p_value);
  127. }
  128. };
  129. class SafeFlag {
  130. std::atomic_bool flag;
  131. static_assert(std::atomic_bool::is_always_lock_free);
  132. public:
  133. _ALWAYS_INLINE_ bool is_set() const {
  134. return flag.load(std::memory_order_acquire);
  135. }
  136. _ALWAYS_INLINE_ void set() {
  137. flag.store(true, std::memory_order_release);
  138. }
  139. _ALWAYS_INLINE_ void clear() {
  140. flag.store(false, std::memory_order_release);
  141. }
  142. _ALWAYS_INLINE_ void set_to(bool p_value) {
  143. flag.store(p_value, std::memory_order_release);
  144. }
  145. _ALWAYS_INLINE_ explicit SafeFlag(bool p_value = false) {
  146. set_to(p_value);
  147. }
  148. };
  149. class SafeRefCount {
  150. SafeNumeric<uint32_t> count;
  151. #ifdef DEV_ENABLED
  152. _ALWAYS_INLINE_ void _check_unref_sanity() {
  153. // This won't catch every misuse, but it's better than nothing.
  154. CRASH_COND_MSG(count.get() == 0,
  155. "Trying to unreference a SafeRefCount which is already zero is wrong and a symptom of it being misused.\n"
  156. "Upon a SafeRefCount reaching zero any object whose lifetime is tied to it, as well as the ref count itself, must be destroyed.\n"
  157. "Moreover, to guarantee that, no multiple threads should be racing to do the final unreferencing to zero.");
  158. }
  159. #endif
  160. public:
  161. _ALWAYS_INLINE_ bool ref() { // true on success
  162. return count.conditional_increment() != 0;
  163. }
  164. _ALWAYS_INLINE_ uint32_t refval() { // none-zero on success
  165. return count.conditional_increment();
  166. }
  167. _ALWAYS_INLINE_ bool unref() { // true if must be disposed of
  168. #ifdef DEV_ENABLED
  169. _check_unref_sanity();
  170. #endif
  171. return count.decrement() == 0;
  172. }
  173. _ALWAYS_INLINE_ uint32_t unrefval() { // 0 if must be disposed of
  174. #ifdef DEV_ENABLED
  175. _check_unref_sanity();
  176. #endif
  177. return count.decrement();
  178. }
  179. _ALWAYS_INLINE_ uint32_t get() const {
  180. return count.get();
  181. }
  182. _ALWAYS_INLINE_ void init(uint32_t p_value = 1) {
  183. count.set(p_value);
  184. }
  185. };
  186. #endif // SAFE_REFCOUNT_H