semaphore.h 5.9 KB

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