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