All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
AtomicOps.h
1 // Copyright eeGeo Ltd (2012-2014), All Rights Reserved
2 
3 #pragma once
4 
5 #include "Types.h"
6 #if defined(EEGEO_IOS) || defined(EEGEO_OSX)
7 #include <libkern/OSAtomic.h>
8 #include <atomic>
9 #elif defined(EEGEO_WIN)
10 #include "EegeoWindowsGuard.h"
11 #endif
12 
13 namespace Eegeo
14 {
15  namespace Concurrency
16  {
17  inline bool AtomicCompareAndSwap32(s32 oldValue, s32 newValue, volatile s32* theValue)
18  {
19 #if defined(EEGEO_IOS)
20  return OSAtomicCompareAndSwap32Barrier((int32_t)oldValue, (int32_t)newValue, (volatile int32_t*)theValue);
21 #elif defined(EEGEO_OSX)
22  return std::atomic_compare_exchange_strong((volatile std::atomic<int32_t>*)theValue, (int32_t*)&oldValue, (int32_t)newValue);
23 #elif defined EEGEO_DROID || defined(EMSCRIPTEN)
24  return __sync_bool_compare_and_swap(theValue, oldValue, newValue);
25 #elif defined EEGEO_WIN
26  return InterlockedCompareExchange((volatile long*)theValue, (long)newValue, (long)oldValue) == oldValue;
27 #endif
28  }
29 
30  inline s32 AtomicIncrement32(volatile s32* theValue)
31  {
32  // return new value after increment
33 #if defined(EEGEO_IOS)
34  return OSAtomicIncrement32Barrier((volatile int32_t*)theValue);
35 #elif defined(EEGEO_OSX)
36  return std::atomic_fetch_add((volatile std::atomic<int32_t>*)theValue, (int32_t)1);
37 #elif defined EEGEO_DROID || defined(EMSCRIPTEN)
38  return __sync_fetch_and_add(theValue, (s32)1);
39 #elif defined EEGEO_WIN
40  return InterlockedIncrement((LONG volatile *)theValue);
41 #endif
42  }
43 
44  inline s64 AtomicIncrement64(volatile s64* theValue)
45  {
46 #if defined(EEGEO_WIN)
47  return (uint64_t)InterlockedIncrement64(theValue);
48 #elif defined(EEGEO_IOS)
49  return(uint64_t)OSAtomicIncrement64(theValue);
50 #elif defined(EEGEO_OSX)
51  return (uint64_t)std::atomic_fetch_add((volatile std::atomic<uint64_t>*)theValue, (uint64_t)1);
52 #else
53  return __sync_fetch_and_add(theValue, 1);
54 #endif
55  }
56 
57  inline s32 AtomicDecrement32(volatile s32* theValue)
58  {
59  // return new value after decrement
60 #if defined(EEGEO_IOS)
61  return OSAtomicDecrement32Barrier((volatile int32_t*)theValue);
62 #elif defined(EEGEO_OSX)
63  return std::atomic_fetch_sub((volatile std::atomic<int32_t>*)theValue, (int32_t)1);
64 #elif defined EEGEO_DROID || defined(EMSCRIPTEN)
65  return __sync_fetch_and_sub(theValue, (s32)1);
66 #elif defined EEGEO_WIN
67  return InterlockedDecrement((LONG volatile *)theValue);
68 #endif
69  }
70  }
71 }