semaphore.h 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. /**************************************************************************/
  2. /* semaphore.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 SEMAPHORE_H
  31. #define SEMAPHORE_H
  32. #include <cstdint>
  33. #ifdef THREADS_ENABLED
  34. #include "core/error/error_list.h"
  35. #include "core/typedefs.h"
  36. #ifdef DEBUG_ENABLED
  37. #include "core/error/error_macros.h"
  38. #endif
  39. #ifdef MINGW_ENABLED
  40. #define MINGW_STDTHREAD_REDUNDANCY_WARNING
  41. #include "thirdparty/mingw-std-threads/mingw.condition_variable.h"
  42. #include "thirdparty/mingw-std-threads/mingw.mutex.h"
  43. #define THREADING_NAMESPACE mingw_stdthread
  44. #else
  45. #include <condition_variable>
  46. #include <mutex>
  47. #define THREADING_NAMESPACE std
  48. #endif
  49. class Semaphore {
  50. private:
  51. mutable THREADING_NAMESPACE::mutex mutex;
  52. mutable THREADING_NAMESPACE::condition_variable condition;
  53. mutable uint32_t count = 0; // Initialized as locked.
  54. #ifdef DEBUG_ENABLED
  55. mutable uint32_t awaiters = 0;
  56. #endif
  57. public:
  58. _ALWAYS_INLINE_ void post(uint32_t p_count = 1) const {
  59. std::lock_guard lock(mutex);
  60. count += p_count;
  61. for (uint32_t i = 0; i < p_count; ++i) {
  62. condition.notify_one();
  63. }
  64. }
  65. _ALWAYS_INLINE_ void wait() const {
  66. THREADING_NAMESPACE::unique_lock lock(mutex);
  67. #ifdef DEBUG_ENABLED
  68. ++awaiters;
  69. #endif
  70. while (!count) { // Handle spurious wake-ups.
  71. condition.wait(lock);
  72. }
  73. --count;
  74. #ifdef DEBUG_ENABLED
  75. --awaiters;
  76. #endif
  77. }
  78. _ALWAYS_INLINE_ bool try_wait() const {
  79. std::lock_guard lock(mutex);
  80. if (count) {
  81. count--;
  82. return true;
  83. } else {
  84. return false;
  85. }
  86. }
  87. #ifdef DEBUG_ENABLED
  88. ~Semaphore() {
  89. // Destroying an std::condition_variable when not all threads waiting on it have been notified
  90. // invokes undefined behavior (e.g., it may be nicely destroyed or it may be awaited forever.)
  91. // That means other threads could still be running the body of std::condition_variable::wait()
  92. // but already past the safety checkpoint. That's the case for instance if that function is already
  93. // waiting to lock again.
  94. //
  95. // We will make the rule a bit more restrictive and simpler to understand at the same time: there
  96. // should not be any threads at any stage of the waiting by the time the semaphore is destroyed.
  97. //
  98. // We do so because of the following reasons:
  99. // - We have the guideline that threads must be awaited (i.e., completed), so the waiting thread
  100. // must be completely done by the time the thread controlling it finally destroys the semaphore.
  101. // Therefore, only a coding mistake could make the program run into such a attempt at premature
  102. // destruction of the semaphore.
  103. // - In scripting, given that Semaphores are wrapped by RefCounted classes, in general it can't
  104. // happen that a thread is trying to destroy a Semaphore while another is still doing whatever with
  105. // it, so the simplification is mostly transparent to script writers.
  106. // - The redefined rule can be checked for failure to meet it, which is what this implementation does.
  107. // This is useful to detect a few cases of potential misuse; namely:
  108. // a) In scripting:
  109. // * The coder is naughtily dealing with the reference count causing a semaphore to die prematurely.
  110. // * The coder is letting the project reach its termination without having cleanly finished threads
  111. // that await on semaphores (or at least, let the usual semaphore-controlled loop exit).
  112. // b) In the native side, where Semaphore is not a ref-counted beast and certain coding mistakes can
  113. // lead to its premature destruction as well.
  114. //
  115. // Let's let users know they are doing it wrong, but apply a, somewhat hacky, countermeasure against UB
  116. // in debug builds.
  117. std::lock_guard lock(mutex);
  118. if (awaiters) {
  119. WARN_PRINT(
  120. "A Semaphore object is being destroyed while one or more threads are still waiting on it.\n"
  121. "Please call post() on it as necessary to prevent such a situation and so ensure correct cleanup.");
  122. // And now, the hacky countermeasure (i.e., leak the condition variable).
  123. new (&condition) THREADING_NAMESPACE::condition_variable();
  124. }
  125. }
  126. #endif
  127. };
  128. #else // No threads.
  129. class Semaphore {
  130. public:
  131. void post(uint32_t p_count = 1) const {}
  132. void wait() const {}
  133. bool try_wait() const {
  134. return true;
  135. }
  136. };
  137. #endif // THREADS_ENABLED
  138. #endif // SEMAPHORE_H