semaphore.h 5.6 KB

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