Debian Codegraph @

srtcore/atomic.h

raw
1 //----------------------------------------------------------------------------
2 // This is free and unencumbered software released into the public domain.
3 //
4 // Anyone is free to copy, modify, publish, use, compile, sell, or distribute
5 // this software, either in source code form or as a compiled binary, for any
6 // purpose, commercial or non-commercial, and by any means.
7 //
8 // In jurisdictions that recognize copyright laws, the author or authors of
9 // this software dedicate any and all copyright interest in the software to the
10 // public domain. We make this dedication for the benefit of the public at
11 // large and to the detriment of our heirs and successors. We intend this
12 // dedication to be an overt act of relinquishment in perpetuity of all present
13 // and future rights to this software under copyright law.
14 //
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
19 // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 //
22 // For more information, please refer to <http://unlicense.org/>
23 //-----------------------------------------------------------------------------
24
25 // SRT Project information:
26 // This file was adopted from a Public Domain project from
27 // https://github.com/mbitsnbites/atomic
28 // Only namespaces were changed to adopt it for SRT project.
29
30 #ifndef SRT_SYNC_ATOMIC_H_
31 #define SRT_SYNC_ATOMIC_H_
32
33 // Macro for disallowing copying of an object.
34 #if __cplusplus >= 201103L
35 #define ATOMIC_DISALLOW_COPY(T) \
36 T(const T&) = delete; \
37 T& operator=(const T&) = delete;
38 #else
39 #define ATOMIC_DISALLOW_COPY(T) \
40 T(const T&); \
41 T& operator=(const T&);
42 #endif
43
44 // A portable static assert.
45 #if __cplusplus >= 201103L
46 #define ATOMIC_STATIC_ASSERT(condition, message) \
47 static_assert((condition), message)
48 #else
49 // Based on: http://stackoverflow.com/a/809465/5778708
50 #define ATOMIC_STATIC_ASSERT(condition, message) \
51 _impl_STATIC_ASSERT_LINE(condition, __LINE__)
52 #define _impl_PASTE(a, b) a##b
53 #ifdef __GNUC__
54 #define _impl_UNUSED __attribute__((__unused__))
55 #else
56 #define _impl_UNUSED
57 #endif
58 #define _impl_STATIC_ASSERT_LINE(condition, line) \
59 typedef char _impl_PASTE( \
60 STATIC_ASSERT_failed_, \
61 line)[(2 * static_cast<int>(!!(condition))) - 1] _impl_UNUSED
62 #endif
63
64 #if defined(ATOMIC_USE_SRT_SYNC_MUTEX) && (ATOMIC_USE_SRT_SYNC_MUTEX == 1)
65 // NOTE: Defined at the top level.
66 #elif __cplusplus >= 201103L
67 // NOTE: Prefer to use the c++11 std::atomic.
68 #define ATOMIC_USE_CPP11_ATOMIC
69 #elif (defined(__clang__) && defined(__clang_major__) && (__clang_major__ > 5)) \
70 || defined(__xlc__)
71 // NOTE: Clang <6 does not support GCC __atomic_* intrinsics. I am unsure
72 // about Clang6. Since Clang sets __GNUC__ and __GNUC_MINOR__ of this era
73 // to <4.5, older Clang will catch the setting below to use the
74 // POSIX Mutex Implementation.
75 #define ATOMIC_USE_GCC_INTRINSICS
76 #elif defined(__GNUC__) \
77 && ( (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)) )
78 // NOTE: The __atomic_* family of intrinsics were introduced in GCC-4.7.0.
79 // NOTE: This follows #if defined(__clang__), because most if, not all,
80 // versions of Clang define __GNUC__ and __GNUC_MINOR__ but often define
81 // them to 4.4 or an even earlier version. Most of the newish versions
82 // of Clang also support GCC Atomic Intrinsics even if they set GCC version
83 // macros to <4.7.
84 #define ATOMIC_USE_GCC_INTRINSICS
85 #elif defined(__GNUC__) && !defined(ATOMIC_USE_SRT_SYNC_MUTEX)
86 // NOTE: GCC compiler built-ins for atomic operations are pure
87 // compiler extensions prior to GCC-4.7 and were grouped into the
88 // the __sync_* family of functions. GCC-4.7, both the c++11 and C11
89 // standards had been finalized, and GCC updated their built-ins to
90 // better reflect the new memory model and the new functions grouped
91 // into the __atomic_* family. Also the memory models were defined
92 // differently, than in pre 4.7.
93 // TODO: PORT to the pre GCC-4.7 __sync_* intrinsics. In the meantime use
94 // the POSIX Mutex Implementation.
95 #define ATOMIC_USE_SRT_SYNC_MUTEX 1
96 #elif defined(_MSC_VER)
97 #define ATOMIC_USE_MSVC_INTRINSICS
98 #include "atomic_msvc.h"
99 #else
100 #error Unsupported compiler / system.
101 #endif
102 // Include any necessary headers for the selected Atomic Implementation.
103 #if defined(ATOMIC_USE_SRT_SYNC_MUTEX) && (ATOMIC_USE_SRT_SYNC_MUTEX == 1)
104 #include "sync.h"
105 #endif
106 #if defined(ATOMIC_USE_CPP11_ATOMIC)
107 #include <atomic>
108 #endif
109
110 namespace srt {
111 namespace sync {
112 template <typename T>
113 class atomic {
114 public:
115 ATOMIC_STATIC_ASSERT(sizeof(T) == 1 || sizeof(T) == 2 || sizeof(T) == 4 ||
116 sizeof(T) == 8,
117 "Only types of size 1, 2, 4 or 8 are supported");
118
119 atomic()
120 : value_(static_cast<T>(0))
121 #if defined(ATOMIC_USE_SRT_SYNC_MUTEX) && (ATOMIC_USE_SRT_SYNC_MUTEX == 1)
122 , mutex_()
123 #endif
124 {
125 // No-Op
126 }
127
128 explicit atomic(const T value)
129 : value_(value)
130 #if defined(ATOMIC_USE_SRT_SYNC_MUTEX) && (ATOMIC_USE_SRT_SYNC_MUTEX == 1)
131 , mutex_()
132 #endif
133 {
134 // No-Op
135 }
136
137 ~atomic()
138 {
139 // No-Op
140 }
141
142 /// @brief Performs an atomic increment operation (value + 1).
143 /// @returns The new value of the atomic object.
144 T operator++() {
145 #if defined(ATOMIC_USE_SRT_SYNC_MUTEX) && (ATOMIC_USE_SRT_SYNC_MUTEX == 1)
146 ScopedLock lg_(mutex_);
147 const T t = ++value_;
148 return t;
149 #elif defined(ATOMIC_USE_GCC_INTRINSICS)
150 return __atomic_add_fetch(&value_, 1, __ATOMIC_SEQ_CST);
151 #elif defined(ATOMIC_USE_MSVC_INTRINSICS)
152 return msvc::interlocked<T>::increment(&value_);
153 #elif defined(ATOMIC_USE_CPP11_ATOMIC)
154 return ++value_;
155 #else
156 #error "Implement Me."
157 #endif
158 }
159
160 /// @brief Performs an atomic decrement operation (value - 1).
161 /// @returns The new value of the atomic object.
162 T operator--() {
163 #if defined(ATOMIC_USE_SRT_SYNC_MUTEX) && (ATOMIC_USE_SRT_SYNC_MUTEX == 1)
164 ScopedLock lg_(mutex_);
165 const T t = --value_;
166 return t;
167 #elif defined(ATOMIC_USE_GCC_INTRINSICS)
168 return __atomic_sub_fetch(&value_, 1, __ATOMIC_SEQ_CST);
169 #elif defined(ATOMIC_USE_MSVC_INTRINSICS)
170 return msvc::interlocked<T>::decrement(&value_);
171 #elif defined(ATOMIC_USE_CPP11_ATOMIC)
172 return --value_;
173 #else
174 #error "Implement Me."
175 #endif
176 }
177
178 T operator|=(T i) {
179 #if defined(ATOMIC_USE_SRT_SYNC_MUTEX) && (ATOMIC_USE_SRT_SYNC_MUTEX == 1)
180 ScopedLock lg_(mutex_);
181 const T t = value_ |= i;
182 return t;
183 #elif defined(ATOMIC_USE_GCC_INTRINSICS)
184 return __atomic_or_fetch(&value_, i, __ATOMIC_SEQ_CST);
185 #elif defined(ATOMIC_USE_MSVC_INTRINSICS)
186 return msvc::interlocked<T>::or_fetch(&value_, i);
187 #elif defined(ATOMIC_USE_CPP11_ATOMIC)
188 return value_ |= i;
189 #else
190 #error "Implement Me."
191 #endif
192 }
193
194 /// @brief Performs an atomic compare-and-swap (CAS) operation.
195 ///
196 /// The value of the atomic object is only updated to the new value if the
197 /// old value of the atomic object matches @c expected_val.
198 ///
199 /// @param expected_val The expected value of the atomic object.
200 /// @param new_val The new value to write to the atomic object.
201 /// @returns True if new_value was written to the atomic object.
202 bool compare_exchange(const T expected_val, const T new_val) {
203 #if defined(ATOMIC_USE_SRT_SYNC_MUTEX) && (ATOMIC_USE_SRT_SYNC_MUTEX == 1)
204 ScopedLock lg_(mutex_);
205 bool result = false;
206 if (expected_val == value_)
207 {
208 value_ = new_val;
209 result = true;
210 }
211 return result;
212 #elif defined(ATOMIC_USE_GCC_INTRINSICS)
213 T e = expected_val;
214 return __atomic_compare_exchange_n(
215 &value_, &e, new_val, true, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
216 #elif defined(ATOMIC_USE_MSVC_INTRINSICS)
217 const T old_val =
218 msvc::interlocked<T>::compare_exchange(&value_, new_val, expected_val);
219 return (old_val == expected_val);
220 #elif defined(ATOMIC_USE_CPP11_ATOMIC)
221 T e = expected_val;
222 return value_.compare_exchange_weak(e, new_val);
223 #else
224 #error "Implement Me."
225 #endif
226 }
227
228 /// @brief Performs an atomic set operation.
229 ///
230 /// The value of the atomic object is unconditionally updated to the new
231 /// value.
232 ///
233 /// @param new_val The new value to write to the atomic object.
234 void store(const T new_val) {
235 #if defined(ATOMIC_USE_SRT_SYNC_MUTEX) && (ATOMIC_USE_SRT_SYNC_MUTEX == 1)
236 ScopedLock lg_(mutex_);
237 value_ = new_val;
238 #elif defined(ATOMIC_USE_GCC_INTRINSICS)
239 __atomic_store_n(&value_, new_val, __ATOMIC_SEQ_CST);
240 #elif defined(ATOMIC_USE_MSVC_INTRINSICS)
241 (void)msvc::interlocked<T>::exchange(&value_, new_val);
242 #elif defined(ATOMIC_USE_CPP11_ATOMIC)
243 value_.store(new_val);
244 #else
245 #error "Implement Me."
246 #endif
247 }
248
249 /// @returns the current value of the atomic object.
250 /// @note Be careful about how this is used, since any operations on the
251 /// returned value are inherently non-atomic.
252 T load() const {
253 #if defined(ATOMIC_USE_SRT_SYNC_MUTEX) && (ATOMIC_USE_SRT_SYNC_MUTEX == 1)
254 ScopedLock lg_(mutex_);
255 const T t = value_;
256 return t;
257 #elif defined(ATOMIC_USE_GCC_INTRINSICS)
258 return __atomic_load_n(&value_, __ATOMIC_SEQ_CST);
259 #elif defined(ATOMIC_USE_MSVC_INTRINSICS)
260 // TODO(m): Is there a better solution for MSVC?
261 return value_;
262 #elif defined(ATOMIC_USE_CPP11_ATOMIC)
263 return value_;
264 #else
265 #error "Implement Me."
266 #endif
267 }
268
269 /// @brief Performs an atomic exchange operation.
270 ///
271 /// The value of the atomic object is unconditionally updated to the new
272 /// value, and the old value is returned.
273 ///
274 /// @param new_val The new value to write to the atomic object.
275 /// @returns the old value.
276 T exchange(const T new_val) {
277 #if defined(ATOMIC_USE_SRT_SYNC_MUTEX) && (ATOMIC_USE_SRT_SYNC_MUTEX == 1)
278 ScopedLock lg_(mutex_);
279 const T t = value_;
280 value_ = new_val;
281 return t;
282 #elif defined(ATOMIC_USE_GCC_INTRINSICS)
283 return __atomic_exchange_n(&value_, new_val, __ATOMIC_SEQ_CST);
284 #elif defined(ATOMIC_USE_MSVC_INTRINSICS)
285 return msvc::interlocked<T>::exchange(&value_, new_val);
286 #elif defined(ATOMIC_USE_CPP11_ATOMIC)
287 return value_.exchange(new_val);
288 #else
289 #error "Implement Me."
290 #endif
291 }
292
293 T operator=(const T new_value) {
294 store(new_value);
295 return new_value;
296 }
297
298 operator T() const {
299 return load();
300 }
301
302 private:
303 #if defined(ATOMIC_USE_SRT_SYNC_MUTEX) && (ATOMIC_USE_SRT_SYNC_MUTEX == 1)
304 T value_;
305 mutable Mutex mutex_;
306 #elif defined(ATOMIC_USE_GCC_INTRINSICS)
307 volatile T value_;
308 #elif defined(ATOMIC_USE_MSVC_INTRINSICS)
309 volatile T value_;
310 #elif defined(ATOMIC_USE_CPP11_ATOMIC)
311 std::atomic<T> value_;
312 #else
313 #error "Implement Me. (value_ type)"
314 #endif
315
316 ATOMIC_DISALLOW_COPY(atomic)
317 };
318
319 } // namespace sync
320 } // namespace srt
321
322 // Undef temporary defines.
323 #undef ATOMIC_USE_GCC_INTRINSICS
324 #undef ATOMIC_USE_MSVC_INTRINSICS
325 #undef ATOMIC_USE_CPP11_ATOMIC
326
327 #endif // ATOMIC_ATOMIC_H_