SDL_atomic.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2013 Sam Lantinga <slouken@libsdl.org>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. /**
  19. * \file SDL_atomic.h
  20. *
  21. * Atomic operations.
  22. *
  23. * IMPORTANT:
  24. * If you are not an expert in concurrent lockless programming, you should
  25. * only be using the atomic lock and reference counting functions in this
  26. * file. In all other cases you should be protecting your data structures
  27. * with full mutexes.
  28. *
  29. * The list of "safe" functions to use are:
  30. * SDL_AtomicLock()
  31. * SDL_AtomicUnlock()
  32. * SDL_AtomicIncRef()
  33. * SDL_AtomicDecRef()
  34. *
  35. * Seriously, here be dragons!
  36. * ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  37. *
  38. * You can find out a little more about lockless programming and the
  39. * subtle issues that can arise here:
  40. * http://msdn.microsoft.com/en-us/library/ee418650%28v=vs.85%29.aspx
  41. *
  42. * There's also lots of good information here:
  43. * http://www.1024cores.net/home/lock-free-algorithms
  44. * http://preshing.com/
  45. *
  46. * These operations may or may not actually be implemented using
  47. * processor specific atomic operations. When possible they are
  48. * implemented as true processor specific atomic operations. When that
  49. * is not possible the are implemented using locks that *do* use the
  50. * available atomic operations.
  51. *
  52. * All of the atomic operations that modify memory are full memory barriers.
  53. */
  54. #ifndef _SDL_atomic_h_
  55. #define _SDL_atomic_h_
  56. #include "SDL_stdinc.h"
  57. #include "SDL_platform.h"
  58. #include "begin_code.h"
  59. /* Need to do this here because intrin.h has C++ code in it */
  60. /* Visual Studio 2005 has a bug where intrin.h conflicts with winnt.h */
  61. #if defined(_MSC_VER) && (_MSC_VER >= 1500)
  62. #include <intrin.h>
  63. #define HAVE_MSC_ATOMICS 1
  64. #endif
  65. /* Set up for C function definitions, even when using C++ */
  66. #ifdef __cplusplus
  67. extern "C" {
  68. #endif
  69. /**
  70. * \name SDL AtomicLock
  71. *
  72. * The atomic locks are efficient spinlocks using CPU instructions,
  73. * but are vulnerable to starvation and can spin forever if a thread
  74. * holding a lock has been terminated. For this reason you should
  75. * minimize the code executed inside an atomic lock and never do
  76. * expensive things like API or system calls while holding them.
  77. *
  78. * The atomic locks are not safe to lock recursively.
  79. *
  80. * Porting Note:
  81. * The spin lock functions and type are required and can not be
  82. * emulated because they are used in the atomic emulation code.
  83. */
  84. /*@{*/
  85. typedef int SDL_SpinLock;
  86. /**
  87. * \brief Try to lock a spin lock by setting it to a non-zero value.
  88. *
  89. * \param lock Points to the lock.
  90. *
  91. * \return SDL_TRUE if the lock succeeded, SDL_FALSE if the lock is already held.
  92. */
  93. extern DECLSPEC SDL_bool SDLCALL SDL_AtomicTryLock(SDL_SpinLock *lock);
  94. /**
  95. * \brief Lock a spin lock by setting it to a non-zero value.
  96. *
  97. * \param lock Points to the lock.
  98. */
  99. extern DECLSPEC void SDLCALL SDL_AtomicLock(SDL_SpinLock *lock);
  100. /**
  101. * \brief Unlock a spin lock by setting it to 0. Always returns immediately
  102. *
  103. * \param lock Points to the lock.
  104. */
  105. extern DECLSPEC void SDLCALL SDL_AtomicUnlock(SDL_SpinLock *lock);
  106. /*@}*//*SDL AtomicLock*/
  107. /**
  108. * The compiler barrier prevents the compiler from reordering
  109. * reads and writes to globally visible variables across the call.
  110. */
  111. #if defined(_MSC_VER) && (_MSC_VER > 1200)
  112. void _ReadWriteBarrier(void);
  113. #pragma intrinsic(_ReadWriteBarrier)
  114. #define SDL_CompilerBarrier() _ReadWriteBarrier()
  115. #elif defined(__GNUC__)
  116. #define SDL_CompilerBarrier() __asm__ __volatile__ ("" : : : "memory")
  117. #else
  118. #define SDL_CompilerBarrier() \
  119. { SDL_SpinLock _tmp = 0; SDL_AtomicLock(&_tmp); SDL_AtomicUnlock(&_tmp); }
  120. #endif
  121. /**
  122. * Memory barriers are designed to prevent reads and writes from being
  123. * reordered by the compiler and being seen out of order on multi-core CPUs.
  124. *
  125. * A typical pattern would be for thread A to write some data and a flag,
  126. * and for thread B to read the flag and get the data. In this case you
  127. * would insert a release barrier between writing the data and the flag,
  128. * guaranteeing that the data write completes no later than the flag is
  129. * written, and you would insert an acquire barrier between reading the
  130. * flag and reading the data, to ensure that all the reads associated
  131. * with the flag have completed.
  132. *
  133. * In this pattern you should always see a release barrier paired with
  134. * an acquire barrier and you should gate the data reads/writes with a
  135. * single flag variable.
  136. *
  137. * For more information on these semantics, take a look at the blog post:
  138. * http://preshing.com/20120913/acquire-and-release-semantics
  139. */
  140. #if defined(__GNUC__) && (defined(__powerpc__) || defined(__ppc__))
  141. #define SDL_MemoryBarrierRelease() __asm__ __volatile__ ("lwsync" : : : "memory")
  142. #define SDL_MemoryBarrierAcquire() __asm__ __volatile__ ("lwsync" : : : "memory")
  143. #elif defined(__GNUC__) && defined(__arm__)
  144. #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__)
  145. #define SDL_MemoryBarrierRelease() __asm__ __volatile__ ("dmb ish" : : : "memory")
  146. #define SDL_MemoryBarrierAcquire() __asm__ __volatile__ ("dmb ish" : : : "memory")
  147. #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__)
  148. #ifdef __thumb__
  149. /* The mcr instruction isn't available in thumb mode, use real functions */
  150. extern DECLSPEC void SDLCALL SDL_MemoryBarrierRelease();
  151. extern DECLSPEC void SDLCALL SDL_MemoryBarrierAcquire();
  152. #else
  153. #define SDL_MemoryBarrierRelease() __asm__ __volatile__ ("mcr p15, 0, %0, c7, c10, 5" : : "r"(0) : "memory")
  154. #define SDL_MemoryBarrierAcquire() __asm__ __volatile__ ("mcr p15, 0, %0, c7, c10, 5" : : "r"(0) : "memory")
  155. #endif /* __thumb__ */
  156. #else
  157. #define SDL_MemoryBarrierRelease() __asm__ __volatile__ ("" : : : "memory")
  158. #define SDL_MemoryBarrierAcquire() __asm__ __volatile__ ("" : : : "memory")
  159. #endif /* __GNUC__ && __arm__ */
  160. #else
  161. /* This is correct for the x86 and x64 CPUs, and we'll expand this over time. */
  162. #define SDL_MemoryBarrierRelease() SDL_CompilerBarrier()
  163. #define SDL_MemoryBarrierAcquire() SDL_CompilerBarrier()
  164. #endif
  165. /* Platform specific optimized versions of the atomic functions,
  166. * you can disable these by defining SDL_DISABLE_ATOMIC_INLINE
  167. */
  168. #if defined(SDL_ATOMIC_DISABLED) && SDL_ATOMIC_DISABLED
  169. #define SDL_DISABLE_ATOMIC_INLINE
  170. #endif
  171. #ifndef SDL_DISABLE_ATOMIC_INLINE
  172. #ifdef HAVE_MSC_ATOMICS
  173. #define SDL_AtomicSet(a, v) _InterlockedExchange((long*)&(a)->value, (v))
  174. #define SDL_AtomicAdd(a, v) _InterlockedExchangeAdd((long*)&(a)->value, (v))
  175. #define SDL_AtomicCAS(a, oldval, newval) (_InterlockedCompareExchange((long*)&(a)->value, (newval), (oldval)) == (oldval))
  176. #define SDL_AtomicSetPtr(a, v) _InterlockedExchangePointer((a), (v))
  177. #if _M_IX86
  178. #define SDL_AtomicCASPtr(a, oldval, newval) (_InterlockedCompareExchange((long*)(a), (long)(newval), (long)(oldval)) == (long)(oldval))
  179. #else
  180. #define SDL_AtomicCASPtr(a, oldval, newval) (_InterlockedCompareExchangePointer((a), (newval), (oldval)) == (oldval))
  181. #endif
  182. #elif defined(__MACOSX__)
  183. #include <libkern/OSAtomic.h>
  184. #define SDL_AtomicCAS(a, oldval, newval) OSAtomicCompareAndSwap32Barrier((oldval), (newval), &(a)->value)
  185. #ifdef __LP64__
  186. #define SDL_AtomicCASPtr(a, oldval, newval) OSAtomicCompareAndSwap64Barrier((int64_t)(oldval), (int64_t)(newval), (int64_t*)(a))
  187. #else
  188. #define SDL_AtomicCASPtr(a, oldval, newval) OSAtomicCompareAndSwap32Barrier((int32_t)(oldval), (int32_t)(newval), (int32_t*)(a))
  189. #endif
  190. #elif defined(HAVE_GCC_ATOMICS)
  191. #define SDL_AtomicSet(a, v) __sync_lock_test_and_set(&(a)->value, v)
  192. #define SDL_AtomicAdd(a, v) __sync_fetch_and_add(&(a)->value, v)
  193. #define SDL_AtomicSetPtr(a, v) __sync_lock_test_and_set(a, v)
  194. #define SDL_AtomicCAS(a, oldval, newval) __sync_bool_compare_and_swap(&(a)->value, oldval, newval)
  195. #define SDL_AtomicCASPtr(a, oldval, newval) __sync_bool_compare_and_swap(a, oldval, newval)
  196. #endif
  197. #endif /* !SDL_DISABLE_ATOMIC_INLINE */
  198. /**
  199. * \brief A type representing an atomic integer value. It is a struct
  200. * so people don't accidentally use numeric operations on it.
  201. */
  202. #ifndef SDL_atomic_t_defined
  203. typedef struct { int value; } SDL_atomic_t;
  204. #endif
  205. /**
  206. * \brief Set an atomic variable to a new value if it is currently an old value.
  207. *
  208. * \return SDL_TRUE if the atomic variable was set, SDL_FALSE otherwise.
  209. *
  210. * \note If you don't know what this function is for, you shouldn't use it!
  211. */
  212. #ifndef SDL_AtomicCAS
  213. extern DECLSPEC SDL_bool SDLCALL SDL_AtomicCAS(SDL_atomic_t *a, int oldval, int newval);
  214. #endif
  215. /**
  216. * \brief Set an atomic variable to a value.
  217. *
  218. * \return The previous value of the atomic variable.
  219. */
  220. #ifndef SDL_AtomicSet
  221. SDL_FORCE_INLINE int SDL_AtomicSet(SDL_atomic_t *a, int v)
  222. {
  223. int value;
  224. do {
  225. value = a->value;
  226. } while (!SDL_AtomicCAS(a, value, v));
  227. return value;
  228. }
  229. #endif
  230. /**
  231. * \brief Get the value of an atomic variable
  232. */
  233. #ifndef SDL_AtomicGet
  234. SDL_FORCE_INLINE int SDL_AtomicGet(SDL_atomic_t *a)
  235. {
  236. int value = a->value;
  237. SDL_CompilerBarrier();
  238. return value;
  239. }
  240. #endif
  241. /**
  242. * \brief Add to an atomic variable.
  243. *
  244. * \return The previous value of the atomic variable.
  245. *
  246. * \note This same style can be used for any number operation
  247. */
  248. #ifndef SDL_AtomicAdd
  249. SDL_FORCE_INLINE int SDL_AtomicAdd(SDL_atomic_t *a, int v)
  250. {
  251. int value;
  252. do {
  253. value = a->value;
  254. } while (!SDL_AtomicCAS(a, value, (value + v)));
  255. return value;
  256. }
  257. #endif
  258. /**
  259. * \brief Increment an atomic variable used as a reference count.
  260. */
  261. #ifndef SDL_AtomicIncRef
  262. #define SDL_AtomicIncRef(a) SDL_AtomicAdd(a, 1)
  263. #endif
  264. /**
  265. * \brief Decrement an atomic variable used as a reference count.
  266. *
  267. * \return SDL_TRUE if the variable reached zero after decrementing,
  268. * SDL_FALSE otherwise
  269. */
  270. #ifndef SDL_AtomicDecRef
  271. #define SDL_AtomicDecRef(a) (SDL_AtomicAdd(a, -1) == 1)
  272. #endif
  273. /**
  274. * \brief Set a pointer to a new value if it is currently an old value.
  275. *
  276. * \return SDL_TRUE if the pointer was set, SDL_FALSE otherwise.
  277. *
  278. * \note If you don't know what this function is for, you shouldn't use it!
  279. */
  280. #ifndef SDL_AtomicCASPtr
  281. extern DECLSPEC SDL_bool SDLCALL SDL_AtomicCASPtr(void* *a, void *oldval, void *newval);
  282. #endif
  283. /**
  284. * \brief Set a pointer to a value atomically.
  285. *
  286. * \return The previous value of the pointer.
  287. */
  288. #ifndef SDL_AtomicSetPtr
  289. SDL_FORCE_INLINE void* SDL_AtomicSetPtr(void* *a, void* v)
  290. {
  291. void* value;
  292. do {
  293. value = *a;
  294. } while (!SDL_AtomicCASPtr(a, value, v));
  295. return value;
  296. }
  297. #endif
  298. /**
  299. * \brief Get the value of a pointer atomically.
  300. */
  301. #ifndef SDL_AtomicGetPtr
  302. SDL_FORCE_INLINE void* SDL_AtomicGetPtr(void* *a)
  303. {
  304. void* value = *a;
  305. SDL_CompilerBarrier();
  306. return value;
  307. }
  308. #endif
  309. /* Ends C function definitions when using C++ */
  310. #ifdef __cplusplus
  311. }
  312. #endif
  313. #include "close_code.h"
  314. #endif /* _SDL_atomic_h_ */
  315. /* vi: set ts=4 sw=4 expandtab: */