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