semaphore.h 6.1 KB

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