include/SDL_atomic.h
author Sam Lantinga <slouken@libsdl.org>
Tue, 25 Jan 2011 23:23:52 -0800
changeset 5098 470ede30189c
parent 5097 b938ad843e52
child 5135 aee04c635ec6
permissions -rw-r--r--
Added a FIFO test to the atomic test suite.
This is really useful because we might be able to use something like this
for the SDL event queue.
     1 /*
     2     SDL - Simple DirectMedia Layer
     3     Copyright (C) 1997-2010 Sam Lantinga
     4 
     5     This library is free software; you can redistribute it and/or
     6     modify it under the terms of the GNU Lesser General Public
     7     License as published by the Free Software Foundation; either
     8     version 2.1 of the License, or (at your option) any later version.
     9 
    10     This library is distributed in the hope that it will be useful,
    11     but WITHOUT ANY WARRANTY; without even the implied warranty of
    12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    13     Lesser General Public License for more details.
    14 
    15     You should have received a copy of the GNU Lesser General Public
    16     License along with this library; if not, write to the Free Software
    17     Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
    18 
    19     Sam Lantinga
    20     slouken@libsdl.org
    21  */
    22 
    23 /**
    24  * \file SDL_atomic.h
    25  * 
    26  * Atomic operations.
    27  * 
    28  * IMPORTANT:
    29  * If you are not an expert in concurrent lockless programming, you should
    30  * only be using the atomic lock and reference counting functions in this
    31  * file.  In all other cases you should be protecting your data structures
    32  * with full mutexes.
    33  * 
    34  * The list of "safe" functions to use are:
    35  *  SDL_AtomicLock()
    36  *  SDL_AtomicUnlock()
    37  *  SDL_AtomicIncRef()
    38  *  SDL_AtomicDecRef()
    39  * 
    40  * Seriously, here be dragons!
    41  * ^^^^^^^^^^^^^^^^^^^^^^^^^^^
    42  *
    43  * You can find out a little more about lockless programming and the 
    44  * subtle issues that can arise here:
    45  * http://msdn.microsoft.com/en-us/library/ee418650%28v=vs.85%29.aspx
    46  *
    47  * There's also lots of good information here:
    48  * http://www.1024cores.net/home/lock-free-algorithms
    49  *
    50  * These operations may or may not actually be implemented using
    51  * processor specific atomic operations. When possible they are
    52  * implemented as true processor specific atomic operations. When that
    53  * is not possible the are implemented using locks that *do* use the
    54  * available atomic operations.
    55  *
    56  * All of the atomic operations that modify memory are full memory barriers.
    57  */
    58 
    59 #ifndef _SDL_atomic_h_
    60 #define _SDL_atomic_h_
    61 
    62 #include "SDL_stdinc.h"
    63 #include "SDL_platform.h"
    64 
    65 #include "begin_code.h"
    66 
    67 /* Need to do this here because intrin.h has C++ code in it */
    68 /* Visual Studio 2005 has a bug where intrin.h conflicts with winnt.h */
    69 #if defined(_MSC_VER) && (_MSC_VER >= 1500) && !defined(_WIN32_WCE)
    70 #include <intrin.h>
    71 #define HAVE_MSC_ATOMICS 1
    72 #endif
    73 
    74 /* Set up for C function definitions, even when using C++ */
    75 #ifdef __cplusplus
    76 /* *INDENT-OFF* */
    77 extern "C" {
    78 /* *INDENT-ON* */
    79 #endif
    80 
    81 /**
    82  * \name SDL AtomicLock
    83  * 
    84  * The atomic locks are efficient spinlocks using CPU instructions,
    85  * but are vulnerable to starvation and can spin forever if a thread
    86  * holding a lock has been terminated.  For this reason you should
    87  * minimize the code executed inside an atomic lock and never do
    88  * expensive things like API or system calls while holding them.
    89  *
    90  * The atomic locks are not safe to lock recursively.
    91  *
    92  * Porting Note:
    93  * The spin lock functions and type are required and can not be
    94  * emulated because they are used in the atomic emulation code.
    95  */
    96 /*@{*/
    97 
    98 typedef int SDL_SpinLock;
    99 
   100 /**
   101  * \brief Try to lock a spin lock by setting it to a non-zero value.
   102  * 
   103  * \param lock Points to the lock.
   104  *
   105  * \return SDL_TRUE if the lock succeeded, SDL_FALSE if the lock is already held.
   106  */
   107 extern DECLSPEC SDL_bool SDLCALL SDL_AtomicTryLock(SDL_SpinLock *lock);
   108 
   109 /**
   110  * \brief Lock a spin lock by setting it to a non-zero value.
   111  * 
   112  * \param lock Points to the lock.
   113  */
   114 extern DECLSPEC void SDLCALL SDL_AtomicLock(SDL_SpinLock *lock);
   115 
   116 /**
   117  * \brief Unlock a spin lock by setting it to 0. Always returns immediately
   118  *
   119  * \param lock Points to the lock.
   120  */
   121 extern DECLSPEC void SDLCALL SDL_AtomicUnlock(SDL_SpinLock *lock);
   122 
   123 /*@}*//*SDL AtomicLock*/
   124 
   125 
   126 /* The compiler barrier prevents the compiler from reordering
   127    reads and writes to globally visible variables across the call.
   128 */
   129 #ifdef _MSC_VER
   130 void _ReadWriteBarrier(void);
   131 #pragma intrinsic(_ReadWriteBarrier)
   132 #define SDL_CompilerBarrier()   _ReadWriteBarrier()
   133 #elif defined(__GNUC__)
   134 #define SDL_CompilerBarrier()   __asm__ __volatile__ ("" : : : "memory")
   135 #else
   136 #define SDL_CompilerBarrier()   \
   137 ({ SDL_SpinLock _tmp = 0; SDL_AtomicLock(&_tmp); SDL_AtomicUnlock(&_tmp); })
   138 #endif
   139 
   140 /* Platform specific optimized versions of the atomic functions,
   141  * you can disable these by defining SDL_DISABLE_ATOMIC_INLINE
   142  */
   143 #ifndef SDL_DISABLE_ATOMIC_INLINE
   144 
   145 #ifdef HAVE_MSC_ATOMICS
   146 
   147 #define SDL_AtomicSet(a, v)     _InterlockedExchange((long*)&(a)->value, (v))
   148 #define SDL_AtomicAdd(a, v)     _InterlockedExchangeAdd((long*)&(a)->value, (v))
   149 #define SDL_AtomicCAS(a, oldval, newval) (_InterlockedCompareExchange((long*)&(a)->value, (newval), (oldval)) == (oldval))
   150 #define SDL_AtomicSetPtr(a, v)  _InterlockedExchangePointer((a), (v))
   151 #if _M_IX86
   152 #define SDL_AtomicCASPtr(a, oldval, newval) (_InterlockedCompareExchange((long*)(a), (long)(newval), (long)(oldval)) == (long)(oldval))
   153 #else
   154 #define SDL_AtomicCASPtr(a, oldval, newval) (_InterlockedCompareExchangePointer((a), (newval), (oldval)) == (oldval))
   155 #endif
   156 
   157 #elif defined(__MACOSX__)
   158 #include <libkern/OSAtomic.h>
   159 
   160 #define SDL_AtomicCAS(a, oldval, newval) OSAtomicCompareAndSwap32Barrier((oldval), (newval), &(a)->value)
   161 #if SIZEOF_VOIDP == 4
   162 #define SDL_AtomicCASPtr(a, oldval, newval) OSAtomicCompareAndSwap32Barrier((int32_t)(oldval), (int32_t)(newval), (int32_t*)(a))
   163 #elif SIZEOF_VOIDP == 8
   164 #define SDL_AtomicCASPtr(a, oldval, newval) OSAtomicCompareAndSwap64Barrier((int64_t)(oldval), (int64_t)(newval), (int64_t*)(a))
   165 #endif
   166 
   167 #elif defined(HAVE_GCC_ATOMICS)
   168 
   169 #define SDL_AtomicSet(a, v)     __sync_lock_test_and_set(&(a)->value, v)
   170 #define SDL_AtomicAdd(a, v)     __sync_fetch_and_add(&(a)->value, v)
   171 #define SDL_AtomicSetPtr(a, v)  __sync_lock_test_and_set(a, v)
   172 #define SDL_AtomicCAS(a, oldval, newval) __sync_bool_compare_and_swap(&(a)->value, oldval, newval)
   173 #define SDL_AtomicCASPtr(a, oldval, newval) __sync_bool_compare_and_swap(a, oldval, newval)
   174 
   175 #endif
   176 
   177 #endif /* !SDL_DISABLE_ATOMIC_INLINE */
   178 
   179 
   180 /**
   181  * \brief A type representing an atomic integer value.  It is a struct
   182  *        so people don't accidentally use numeric operations on it.
   183  */
   184 #ifndef SDL_atomic_t_defined
   185 typedef struct { int value; } SDL_atomic_t;
   186 #endif
   187 
   188 /**
   189  * \brief Set an atomic variable to a new value if it is currently an old value.
   190  *
   191  * \return SDL_TRUE if the atomic variable was set, SDL_FALSE otherwise.
   192  *
   193  * \note If you don't know what this function is for, you shouldn't use it!
   194 */
   195 #ifndef SDL_AtomicCAS
   196 #define SDL_AtomicCAS SDL_AtomicCAS_
   197 #endif
   198 extern DECLSPEC SDL_bool SDLCALL SDL_AtomicCAS_(SDL_atomic_t *a, int oldval, int newval);
   199 
   200 /**
   201  * \brief Set an atomic variable to a value.
   202  *
   203  * \return The previous value of the atomic variable.
   204  */
   205 #ifndef SDL_AtomicSet
   206 static __inline__ int SDL_AtomicSet(SDL_atomic_t *a, int v)
   207 {
   208     int value;
   209     do {
   210         value = a->value;
   211     } while (!SDL_AtomicCAS(a, value, v));
   212     return value;
   213 }
   214 #endif
   215 
   216 /**
   217  * \brief Get the value of an atomic variable
   218  */
   219 #ifndef SDL_AtomicGet
   220 static __inline__ int SDL_AtomicGet(SDL_atomic_t *a)
   221 {
   222     int value = a->value;
   223     SDL_CompilerBarrier();
   224     return value;
   225 }
   226 #endif
   227 
   228 /**
   229  * \brief Add to an atomic variable.
   230  *
   231  * \return The previous value of the atomic variable.
   232  *
   233  * \note This same style can be used for any number operation
   234  */
   235 #ifndef SDL_AtomicAdd
   236 static __inline__ int SDL_AtomicAdd(SDL_atomic_t *a, int v)
   237 {
   238     int value;
   239     do {
   240         value = a->value;
   241     } while (!SDL_AtomicCAS(a, value, (value + v)));
   242     return value;
   243 }
   244 #endif
   245 
   246 /**
   247  * \brief Increment an atomic variable used as a reference count.
   248  */
   249 #ifndef SDL_AtomicIncRef
   250 #define SDL_AtomicIncRef(a)    SDL_AtomicAdd(a, 1)
   251 #endif
   252 
   253 /**
   254  * \brief Decrement an atomic variable used as a reference count.
   255  *
   256  * \return SDL_TRUE if the variable reached zero after decrementing,
   257  *         SDL_FALSE otherwise
   258  */
   259 #ifndef SDL_AtomicDecRef
   260 #define SDL_AtomicDecRef(a)    (SDL_AtomicAdd(a, -1) == 1)
   261 #endif
   262 
   263 /**
   264  * \brief Set a pointer to a new value if it is currently an old value.
   265  *
   266  * \return SDL_TRUE if the pointer was set, SDL_FALSE otherwise.
   267  *
   268  * \note If you don't know what this function is for, you shouldn't use it!
   269 */
   270 #ifndef SDL_AtomicCASPtr
   271 #define SDL_AtomicCASPtr SDL_AtomicCASPtr_
   272 #endif
   273 extern DECLSPEC SDL_bool SDLCALL SDL_AtomicCASPtr_(void **a, void *oldval, void *newval);
   274 
   275 /**
   276  * \brief Set a pointer to a value atomically.
   277  *
   278  * \return The previous value of the pointer.
   279  */
   280 #ifndef SDL_AtomicSetPtr
   281 static __inline__ void* SDL_AtomicSetPtr(void* *a, void* v)
   282 {
   283     void* value;
   284     do {
   285         value = *a;
   286     } while (!SDL_AtomicCASPtr(a, value, v));
   287     return value;
   288 }
   289 #endif
   290 
   291 /**
   292  * \brief Get the value of a pointer atomically.
   293  */
   294 #ifndef SDL_AtomicGetPtr
   295 static __inline__ void* SDL_AtomicGetPtr(void* *a)
   296 {
   297     void* value = *a;
   298     SDL_CompilerBarrier();
   299     return value;
   300 }
   301 #endif
   302 
   303 
   304 /* Ends C function definitions when using C++ */
   305 #ifdef __cplusplus
   306 /* *INDENT-OFF* */
   307 }
   308 /* *INDENT-ON* */
   309 #endif
   310 
   311 #include "close_code.h"
   312 
   313 #endif /* _SDL_atomic_h_ */
   314 
   315 /* vi: set ts=4 sw=4 expandtab: */