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
31#ifndef SEMAPHORE_H
32#define SEMAPHORE_H
33
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
40#include <condition_variable>
41#include <mutex>
42
43class Semaphore {
44private:
45 mutable std::mutex mutex;
46 mutable std::condition_variable condition;
47 mutable uint32_t count = 0; // Initialized as locked.
48#ifdef DEBUG_ENABLED
49 mutable uint32_t awaiters = 0;
50#endif
51
52public:
53 _ALWAYS_INLINE_ void post() const {
54 std::lock_guard lock(mutex);
55 count++;
56 condition.notify_one();
57 }
58
59 _ALWAYS_INLINE_ void wait() const {
60 std::unique_lock lock(mutex);
61#ifdef DEBUG_ENABLED
62 ++awaiters;
63#endif
64 while (!count) { // Handle spurious wake-ups.
65 condition.wait(lock);
66 }
67 --count;
68#ifdef DEBUG_ENABLED
69 --awaiters;
70#endif
71 }
72
73 _ALWAYS_INLINE_ bool try_wait() const {
74 std::lock_guard lock(mutex);
75 if (count) {
76 count--;
77 return true;
78 } else {
79 return false;
80 }
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) std::condition_variable();
120 }
121 }
122#endif
123};
124
125#endif // SEMAPHORE_H
126