DSL
SyncedInt.h
1 //@AUTOHEADER@BEGIN@
2 /***********************************************************************\
3 | Drift Standard Libraries v1.01 |
4 | Copyright 2010-2023 Drift Solutions / Indy Sams |
5 | Docs and more information available at https://www.driftsolutions.dev |
6 | This file released under the 3-clause BSD license, |
7 | see included DSL.LICENSE.TXT file for details. |
8 \***********************************************************************/
9 //@AUTOHEADER@END@
10 
11 #ifndef _INCLUDE_SYNCEDINT_H_
12 #define _INCLUDE_SYNCEDINT_H_
13 
14 #include <drift/Mutex.h>
15 
26 template <class T>
27 class SyncedInt {
28 #if defined(WIN32)
29 private:
30  T * value;
31 public:
32  SyncedInt() {
33  value = (T *)_aligned_malloc(sizeof(T), 64);
34  *value = 0;
35  }
36  ~SyncedInt() {
37  _aligned_free(value);
38  }
39  T Increment() {
40  if (sizeof(T) == 4) {
41  return InterlockedIncrement((LONG *)value);
42 #if (_WIN32_WINNT >= 0x0600)
43  } else if (sizeof(T) == 8) {
44  return InterlockedIncrement64((LONGLONG *)value);
45 #endif
46 #if (_WIN32_WINNT >= 0x0602)
47  } else if (sizeof(T) == 2) {
48  return InterlockedIncrement16((LONGLONG *)value);
49 #endif
50  } else {
51  printf("SyncedInt: Unsupported int size: %u\n", sizeof(T));
52  }
53  return -1;
54  }
55  T Decrement() {
56  if (sizeof(T) == 4) {
57  return InterlockedDecrement((LONG *)value);
58 #if (_WIN32_WINNT >= 0x0600)
59  } else if (sizeof(T) == 8) {
60  return InterlockedDecrement64((LONGLONG *)value);
61 #endif
62 #if (_WIN32_WINNT >= 0x0602)
63  } else if (sizeof(T) == 2) {
64  return InterlockedDecrement16((LONGLONG *)value);
65 #endif
66  } else {
67  printf("SyncedInt: Unsupported int size: %u\n", sizeof(T));
68  }
69  return -1;
70  }
71  T Get() { return *value; }
72 #else
73 private:
74  T __attribute__((aligned(64))) value;
75 public:
76  SyncedInt() {
77  value = 0;
78  }
79  T Increment() {
80  return __sync_add_and_fetch(&value, 1);
81  }
82  T Decrement() {
83  return __sync_sub_and_fetch(&value, 1);
84  }
85  T Get() { return value; }
86 #endif
87 };
88 
91 #endif // _INCLUDE_SYNCEDINT_H_