SDL 3.0
SDL_atomic.h
Go to the documentation of this file.
1/*
2 Simple DirectMedia Layer
3 Copyright (C) 1997-2024 Sam Lantinga <slouken@libsdl.org>
4
5 This software is provided 'as-is', without any express or implied
6 warranty. In no event will the authors be held liable for any damages
7 arising from the use of this software.
8
9 Permission is granted to anyone to use this software for any purpose,
10 including commercial applications, and to alter it and redistribute it
11 freely, subject to the following restrictions:
12
13 1. The origin of this software must not be misrepresented; you must not
14 claim that you wrote the original software. If you use this software
15 in a product, an acknowledgment in the product documentation would be
16 appreciated but is not required.
17 2. Altered source versions must be plainly marked as such, and must not be
18 misrepresented as being the original software.
19 3. This notice may not be removed or altered from any source distribution.
20*/
21
22/**
23 * \file SDL_atomic.h
24 *
25 * Atomic operations.
26 *
27 * IMPORTANT:
28 * If you are not an expert in concurrent lockless programming, you should
29 * not be using any functions in this file. You should be protecting your
30 * data structures with full mutexes instead.
31 *
32 * Seriously, here be dragons!
33 * ^^^^^^^^^^^^^^^^^^^^^^^^^^^
34 *
35 * You can find out a little more about lockless programming and the
36 * subtle issues that can arise here:
37 * https://learn.microsoft.com/en-us/windows/win32/dxtecharts/lockless-programming
38 *
39 * There's also lots of good information here:
40 * http://www.1024cores.net/home/lock-free-algorithms
41 * http://preshing.com/
42 *
43 * These operations may or may not actually be implemented using
44 * processor specific atomic operations. When possible they are
45 * implemented as true processor specific atomic operations. When that
46 * is not possible the are implemented using locks that *do* use the
47 * available atomic operations.
48 *
49 * All of the atomic operations that modify memory are full memory barriers.
50 */
51
52#ifndef SDL_atomic_h_
53#define SDL_atomic_h_
54
55#include <SDL3/SDL_stdinc.h>
57
58#include <SDL3/SDL_begin_code.h>
59
60/* Set up for C function definitions, even when using C++ */
61#ifdef __cplusplus
62extern "C" {
63#endif
64
65/**
66 * An atomic spinlock.
67 *
68 * The atomic locks are efficient spinlocks using CPU instructions, but are
69 * vulnerable to starvation and can spin forever if a thread holding a lock
70 * has been terminated. For this reason you should minimize the code executed
71 * inside an atomic lock and never do expensive things like API or system
72 * calls while holding them.
73 *
74 * They are also vulnerable to starvation if the thread holding the lock is
75 * lower priority than other threads and doesn't get scheduled. In general you
76 * should use mutexes instead, since they have better performance and
77 * contention behavior.
78 *
79 * The atomic locks are not safe to lock recursively.
80 *
81 * Porting Note: The spin lock functions and type are required and can not be
82 * emulated because they are used in the atomic emulation code.
83 */
84typedef int SDL_SpinLock;
85
86/**
87 * Try to lock a spin lock by setting it to a non-zero value.
88 *
89 * ***Please note that spinlocks are dangerous if you don't know what you're
90 * doing. Please be careful using any sort of spinlock!***
91 *
92 * \param lock a pointer to a lock variable
93 * \returns SDL_TRUE if the lock succeeded, SDL_FALSE if the lock is already
94 * held.
95 *
96 * \since This function is available since SDL 3.0.0.
97 *
98 * \sa SDL_LockSpinlock
99 * \sa SDL_UnlockSpinlock
100 */
101extern DECLSPEC SDL_bool SDLCALL SDL_TryLockSpinlock(SDL_SpinLock *lock);
102
103/**
104 * Lock a spin lock by setting it to a non-zero value.
105 *
106 * ***Please note that spinlocks are dangerous if you don't know what you're
107 * doing. Please be careful using any sort of spinlock!***
108 *
109 * \param lock a pointer to a lock variable
110 *
111 * \since This function is available since SDL 3.0.0.
112 *
113 * \sa SDL_TryLockSpinlock
114 * \sa SDL_UnlockSpinlock
115 */
116extern DECLSPEC void SDLCALL SDL_LockSpinlock(SDL_SpinLock *lock);
117
118/**
119 * Unlock a spin lock by setting it to 0.
120 *
121 * Always returns immediately.
122 *
123 * ***Please note that spinlocks are dangerous if you don't know what you're
124 * doing. Please be careful using any sort of spinlock!***
125 *
126 * \param lock a pointer to a lock variable
127 *
128 * \since This function is available since SDL 3.0.0.
129 *
130 * \sa SDL_LockSpinlock
131 * \sa SDL_TryLockSpinlock
132 */
133extern DECLSPEC void SDLCALL SDL_UnlockSpinlock(SDL_SpinLock *lock);
134
135
136#ifdef SDL_WIKI_DOCUMENTATION_SECTION
137
138/**
139 * Mark a compiler barrier.
140 *
141 * A compiler barrier prevents the compiler from reordering reads and writes
142 * to globally visible variables across the call.
143 *
144 * This macro only prevents the compiler from reordering reads and writes, it
145 * does not prevent the CPU from reordering reads and writes. However, all of
146 * the atomic operations that modify memory are full memory barriers.
147 *
148 * \threadsafety Obviously this macro is safe to use from any thread at any
149 * time, but if you find yourself needing this, you are probably
150 * dealing with some very sensitive code; be careful!
151 *
152 * \since This macro is available since SDL 3.0.0.
153 */
154#define SDL_CompilerBarrier() DoCompilerSpecificReadWriteBarrier()
155#elif defined(_MSC_VER) && (_MSC_VER > 1200) && !defined(__clang__)
156void _ReadWriteBarrier(void);
157#pragma intrinsic(_ReadWriteBarrier)
158#define SDL_CompilerBarrier() _ReadWriteBarrier()
159#elif (defined(__GNUC__) && !defined(SDL_PLATFORM_EMSCRIPTEN)) || (defined(__SUNPRO_C) && (__SUNPRO_C >= 0x5120))
160/* This is correct for all CPUs when using GCC or Solaris Studio 12.1+. */
161#define SDL_CompilerBarrier() __asm__ __volatile__ ("" : : : "memory")
162#elif defined(__WATCOMC__)
163extern __inline void SDL_CompilerBarrier(void);
164#pragma aux SDL_CompilerBarrier = "" parm [] modify exact [];
165#else
166#define SDL_CompilerBarrier() \
167{ SDL_SpinLock _tmp = 0; SDL_LockSpinlock(&_tmp); SDL_UnlockSpinlock(&_tmp); }
168#endif
169
170/**
171 * Insert a memory release barrier.
172 *
173 * Memory barriers are designed to prevent reads and writes from being
174 * reordered by the compiler and being seen out of order on multi-core CPUs.
175 *
176 * A typical pattern would be for thread A to write some data and a flag, and
177 * for thread B to read the flag and get the data. In this case you would
178 * insert a release barrier between writing the data and the flag,
179 * guaranteeing that the data write completes no later than the flag is
180 * written, and you would insert an acquire barrier between reading the flag
181 * and reading the data, to ensure that all the reads associated with the flag
182 * have completed.
183 *
184 * In this pattern you should always see a release barrier paired with an
185 * acquire barrier and you should gate the data reads/writes with a single
186 * flag variable.
187 *
188 * For more information on these semantics, take a look at the blog post:
189 * http://preshing.com/20120913/acquire-and-release-semantics
190 *
191 * \threadsafety Obviously this macro is safe to use from any thread at any
192 * time, but if you find yourself needing this, you are probably
193 * dealing with some very sensitive code; be careful!
194 *
195 * \since This function is available since SDL 3.0.0.
196 */
197extern DECLSPEC void SDLCALL SDL_MemoryBarrierReleaseFunction(void);
198
199/**
200 * Insert a memory acquire barrier.
201 *
202 * Please refer to SDL_MemoryBarrierReleaseFunction for the details!
203 *
204 * \threadsafety Obviously this function is safe to use from any thread at any
205 * time, but if you find yourself needing this, you are probably
206 * dealing with some very sensitive code; be careful!
207 *
208 * \since This function is available since SDL 3.0.0.
209 *
210 * \sa SDL_MemoryBarrierReleaseFunction
211 */
212extern DECLSPEC void SDLCALL SDL_MemoryBarrierAcquireFunction(void);
213
214/* !!! FIXME: this should have documentation! */
215#if defined(__GNUC__) && (defined(__powerpc__) || defined(__ppc__))
216#define SDL_MemoryBarrierRelease() __asm__ __volatile__ ("lwsync" : : : "memory")
217#define SDL_MemoryBarrierAcquire() __asm__ __volatile__ ("lwsync" : : : "memory")
218#elif defined(__GNUC__) && defined(__aarch64__)
219#define SDL_MemoryBarrierRelease() __asm__ __volatile__ ("dmb ish" : : : "memory")
220#define SDL_MemoryBarrierAcquire() __asm__ __volatile__ ("dmb ish" : : : "memory")
221#elif defined(__GNUC__) && defined(__arm__)
222#if 0 /* defined(SDL_PLATFORM_LINUX) || defined(SDL_PLATFORM_ANDROID) */
223/* Information from:
224 https://chromium.googlesource.com/chromium/chromium/+/trunk/base/atomicops_internals_arm_gcc.h#19
225
226 The Linux kernel provides a helper function which provides the right code for a memory barrier,
227 hard-coded at address 0xffff0fa0
228*/
229typedef void (*SDL_KernelMemoryBarrierFunc)();
230#define SDL_MemoryBarrierRelease() ((SDL_KernelMemoryBarrierFunc)0xffff0fa0)()
231#define SDL_MemoryBarrierAcquire() ((SDL_KernelMemoryBarrierFunc)0xffff0fa0)()
232#else
233#if defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7EM__) || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7S__) || defined(__ARM_ARCH_8A__)
234#define SDL_MemoryBarrierRelease() __asm__ __volatile__ ("dmb ish" : : : "memory")
235#define SDL_MemoryBarrierAcquire() __asm__ __volatile__ ("dmb ish" : : : "memory")
236#elif defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6T2__) || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__)
237#ifdef __thumb__
238/* The mcr instruction isn't available in thumb mode, use real functions */
239#define SDL_MEMORY_BARRIER_USES_FUNCTION
240#define SDL_MemoryBarrierRelease() SDL_MemoryBarrierReleaseFunction()
241#define SDL_MemoryBarrierAcquire() SDL_MemoryBarrierAcquireFunction()
242#else
243#define SDL_MemoryBarrierRelease() __asm__ __volatile__ ("mcr p15, 0, %0, c7, c10, 5" : : "r"(0) : "memory")
244#define SDL_MemoryBarrierAcquire() __asm__ __volatile__ ("mcr p15, 0, %0, c7, c10, 5" : : "r"(0) : "memory")
245#endif /* __thumb__ */
246#else
247#define SDL_MemoryBarrierRelease() __asm__ __volatile__ ("" : : : "memory")
248#define SDL_MemoryBarrierAcquire() __asm__ __volatile__ ("" : : : "memory")
249#endif /* SDL_PLATFORM_LINUX || SDL_PLATFORM_ANDROID */
250#endif /* __GNUC__ && __arm__ */
251#else
252#if (defined(__SUNPRO_C) && (__SUNPRO_C >= 0x5120))
253/* This is correct for all CPUs on Solaris when using Solaris Studio 12.1+. */
254#include <mbarrier.h>
255#define SDL_MemoryBarrierRelease() __machine_rel_barrier()
256#define SDL_MemoryBarrierAcquire() __machine_acq_barrier()
257#else
258/* This is correct for the x86 and x64 CPUs, and we'll expand this over time. */
259#define SDL_MemoryBarrierRelease() SDL_CompilerBarrier()
260#define SDL_MemoryBarrierAcquire() SDL_CompilerBarrier()
261#endif
262#endif
263
264/* "REP NOP" is PAUSE, coded for tools that don't know it by that name. */
265#ifdef SDL_WIKI_DOCUMENTATION_SECTION
266
267/**
268 * A macro to insert a CPU-specific "pause" instruction into the program.
269 *
270 * This can be useful in busy-wait loops, as it serves as a hint to the CPU as
271 * to the program's intent; some CPUs can use this to do more efficient
272 * processing. On some platforms, this doesn't do anything, so using this
273 * macro might just be a harmless no-op.
274 *
275 * Note that if you are busy-waiting, there are often more-efficient
276 * approaches with other synchronization primitives: mutexes, semaphores,
277 * condition variables, etc.
278 *
279 * \threadsafety This macro is safe to use from any thread.
280 *
281 * \since This macro is available since SDL 3.0.0.
282 */
283#define SDL_CPUPauseInstruction() DoACPUPauseInACompilerAndArchitectureSpecificWay
284#elif (defined(__GNUC__) || defined(__clang__)) && (defined(__i386__) || defined(__x86_64__))
285 #define SDL_CPUPauseInstruction() __asm__ __volatile__("pause\n") /* Some assemblers can't do REP NOP, so go with PAUSE. */
286#elif (defined(__arm__) && defined(__ARM_ARCH) && __ARM_ARCH >= 7) || defined(__aarch64__)
287 #define SDL_CPUPauseInstruction() __asm__ __volatile__("yield" ::: "memory")
288#elif (defined(__powerpc__) || defined(__powerpc64__))
289 #define SDL_CPUPauseInstruction() __asm__ __volatile__("or 27,27,27");
290#elif (defined(__riscv) && __riscv_xlen == 64)
291 #define SDL_CPUPauseInstruction() __asm__ __volatile__(".insn i 0x0F, 0, x0, x0, 0x010");
292#elif defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64))
293 #define SDL_CPUPauseInstruction() _mm_pause() /* this is actually "rep nop" and not a SIMD instruction. No inline asm in MSVC x86-64! */
294#elif defined(_MSC_VER) && (defined(_M_ARM) || defined(_M_ARM64))
295 #define SDL_CPUPauseInstruction() __yield()
296#elif defined(__WATCOMC__) && defined(__386__)
297 extern __inline void SDL_CPUPauseInstruction(void);
298 #pragma aux SDL_CPUPauseInstruction = ".686p" ".xmm2" "pause"
299#else
300 #define SDL_CPUPauseInstruction()
301#endif
302
303
304/**
305 * A type representing an atomic integer value.
306 *
307 * This can be used to manage a value that is synchronized across multiple
308 * CPUs without a race condition; when an app sets a value with SDL_AtomicSet
309 * all other threads, regardless of the CPU it is running on, will see that
310 * value when retrieved with SDL_AtomicGet, regardless of CPU caches, etc.
311 *
312 * This is also useful for atomic compare-and-swap operations: a thread can
313 * change the value as long as its current value matches expectations. When
314 * done in a loop, one can guarantee data consistency across threads without a
315 * lock (but the usual warnings apply: if you don't know what you're doing, or
316 * you don't do it carefully, you can confidently cause any number of
317 * disasters with this, so in most cases, you _should_ use a mutex instead of
318 * this!).
319 *
320 * This is a struct so people don't accidentally use numeric operations on it
321 * directly. You have to use SDL_Atomic* functions.
322 *
323 * \since This struct is available since SDL 3.0.0.
324 *
325 * \sa SDL_AtomicCompareAndSwap
326 * \sa SDL_AtomicGet
327 * \sa SDL_AtomicSet
328 * \sa SDL_AtomicAdd
329 */
330typedef struct SDL_AtomicInt { int value; } SDL_AtomicInt;
331
332/**
333 * Set an atomic variable to a new value if it is currently an old value.
334 *
335 * ***Note: If you don't know what this function is for, you shouldn't use
336 * it!***
337 *
338 * \param a a pointer to an SDL_AtomicInt variable to be modified
339 * \param oldval the old value
340 * \param newval the new value
341 * \returns SDL_TRUE if the atomic variable was set, SDL_FALSE otherwise.
342 *
343 * \since This function is available since SDL 3.0.0.
344 *
345 * \sa SDL_AtomicCompareAndSwapPointer
346 */
347extern DECLSPEC SDL_bool SDLCALL SDL_AtomicCompareAndSwap(SDL_AtomicInt *a, int oldval, int newval);
348
349/**
350 * Set an atomic variable to a value.
351 *
352 * This function also acts as a full memory barrier.
353 *
354 * ***Note: If you don't know what this function is for, you shouldn't use
355 * it!***
356 *
357 * \param a a pointer to an SDL_AtomicInt variable to be modified
358 * \param v the desired value
359 * \returns the previous value of the atomic variable.
360 *
361 * \since This function is available since SDL 3.0.0.
362 *
363 * \sa SDL_AtomicGet
364 */
365extern DECLSPEC int SDLCALL SDL_AtomicSet(SDL_AtomicInt *a, int v);
366
367/**
368 * Get the value of an atomic variable.
369 *
370 * ***Note: If you don't know what this function is for, you shouldn't use
371 * it!***
372 *
373 * \param a a pointer to an SDL_AtomicInt variable
374 * \returns the current value of an atomic variable.
375 *
376 * \since This function is available since SDL 3.0.0.
377 *
378 * \sa SDL_AtomicSet
379 */
380extern DECLSPEC int SDLCALL SDL_AtomicGet(SDL_AtomicInt *a);
381
382/**
383 * Add to an atomic variable.
384 *
385 * This function also acts as a full memory barrier.
386 *
387 * ***Note: If you don't know what this function is for, you shouldn't use
388 * it!***
389 *
390 * \param a a pointer to an SDL_AtomicInt variable to be modified
391 * \param v the desired value to add
392 * \returns the previous value of the atomic variable.
393 *
394 * \since This function is available since SDL 3.0.0.
395 *
396 * \sa SDL_AtomicDecRef
397 * \sa SDL_AtomicIncRef
398 */
399extern DECLSPEC int SDLCALL SDL_AtomicAdd(SDL_AtomicInt *a, int v);
400
401#ifndef SDL_AtomicIncRef
402
403/**
404 * Increment an atomic variable used as a reference count.
405 *
406 * ***Note: If you don't know what this macro is for, you shouldn't use it!***
407 *
408 * \param a a pointer to an SDL_AtomicInt to increment.
409 * \returns the previous value of the atomic variable.
410 *
411 * \since This macro is available since SDL 3.0.0.
412 *
413 * \sa SDL_AtomicDecRef
414 */
415#define SDL_AtomicIncRef(a) SDL_AtomicAdd(a, 1)
416#endif
417
418#ifndef SDL_AtomicDecRef
419
420/**
421 * Decrement an atomic variable used as a reference count.
422 *
423 * ***Note: If you don't know what this macro is for, you shouldn't use it!***
424 *
425 * \param a a pointer to an SDL_AtomicInt to increment.
426 * \returns SDL_TRUE if the variable reached zero after decrementing,
427 * SDL_FALSE otherwise
428 *
429 * \since This macro is available since SDL 3.0.0.
430 *
431 * \sa SDL_AtomicIncRef
432 */
433#define SDL_AtomicDecRef(a) (SDL_AtomicAdd(a, -1) == 1)
434#endif
435
436/**
437 * Set a pointer to a new value if it is currently an old value.
438 *
439 * ***Note: If you don't know what this function is for, you shouldn't use
440 * it!***
441 *
442 * \param a a pointer to a pointer
443 * \param oldval the old pointer value
444 * \param newval the new pointer value
445 * \returns SDL_TRUE if the pointer was set, SDL_FALSE otherwise.
446 *
447 * \since This function is available since SDL 3.0.0.
448 *
449 * \sa SDL_AtomicCompareAndSwap
450 * \sa SDL_AtomicGetPtr
451 * \sa SDL_AtomicSetPtr
452 */
453extern DECLSPEC SDL_bool SDLCALL SDL_AtomicCompareAndSwapPointer(void **a, void *oldval, void *newval);
454
455/**
456 * Set a pointer to a value atomically.
457 *
458 * ***Note: If you don't know what this function is for, you shouldn't use
459 * it!***
460 *
461 * \param a a pointer to a pointer
462 * \param v the desired pointer value
463 * \returns the previous value of the pointer.
464 *
465 * \since This function is available since SDL 3.0.0.
466 *
467 * \sa SDL_AtomicCompareAndSwapPointer
468 * \sa SDL_AtomicGetPtr
469 */
470extern DECLSPEC void* SDLCALL SDL_AtomicSetPtr(void **a, void* v);
471
472/**
473 * Get the value of a pointer atomically.
474 *
475 * ***Note: If you don't know what this function is for, you shouldn't use
476 * it!***
477 *
478 * \param a a pointer to a pointer
479 * \returns the current value of a pointer.
480 *
481 * \since This function is available since SDL 3.0.0.
482 *
483 * \sa SDL_AtomicCompareAndSwapPointer
484 * \sa SDL_AtomicSetPtr
485 */
486extern DECLSPEC void* SDLCALL SDL_AtomicGetPtr(void **a);
487
488/* Ends C function definitions when using C++ */
489#ifdef __cplusplus
490}
491#endif
492
493#include <SDL3/SDL_close_code.h>
494
495#endif /* SDL_atomic_h_ */
void SDL_MemoryBarrierAcquireFunction(void)
int SDL_AtomicSet(SDL_AtomicInt *a, int v)
void * SDL_AtomicGetPtr(void **a)
#define SDL_CompilerBarrier()
Definition SDL_atomic.h:166
void SDL_MemoryBarrierReleaseFunction(void)
int SDL_AtomicGet(SDL_AtomicInt *a)
int SDL_SpinLock
Definition SDL_atomic.h:84
SDL_bool SDL_AtomicCompareAndSwap(SDL_AtomicInt *a, int oldval, int newval)
#define SDL_CPUPauseInstruction()
Definition SDL_atomic.h:300
SDL_bool SDL_AtomicCompareAndSwapPointer(void **a, void *oldval, void *newval)
void SDL_LockSpinlock(SDL_SpinLock *lock)
int SDL_AtomicAdd(SDL_AtomicInt *a, int v)
void SDL_UnlockSpinlock(SDL_SpinLock *lock)
SDL_bool SDL_TryLockSpinlock(SDL_SpinLock *lock)
void * SDL_AtomicSetPtr(void **a, void *v)
int SDL_bool
Definition SDL_stdinc.h:170