00001 #ifndef _ATOMIC_INT_GENERIC_H 00002 00003 #define _ATOMIC_INT_GENERIC_H 00004 00005 #include "mt.h" 00006 00007 namespace mt{ 00008 00009 class atomicInt 00010 { 00011 public: 00012 atomicInt() 00013 { 00014 _q_value = 0; 00015 } 00016 00017 atomicInt( int value ) 00018 { 00019 _q_value = value; 00020 } 00021 00022 // atomic API 00023 00028 inline int fetchAndAddAcquire( int valueToAdd ) 00029 { 00030 mutexlocker lock(&m); 00031 int originalValue = _q_value; 00032 _q_value += valueToAdd; 00033 return originalValue; 00034 } 00035 00039 inline bool ref() 00040 { 00041 mutexlocker lock(&m); 00042 return ++_q_value != 0; 00043 } 00044 00045 /* 00046 Atomically decrements the _q_value of this QAtomicInt. 00047 Returns true if the new _q_value is non-zero, false otherwise.*/ 00048 inline bool deref() 00049 { 00050 mutexlocker lock(&m); 00051 return --_q_value != 0; 00052 } 00053 00054 /* 00055 If the current _q_value of this QAtomicInt is the expectedValue, 00056 the test-and-set functions assign the newValue to this QAtomicInt 00057 and return true. If the values are not the same, this function 00058 does nothing and returns false. 00059 */ 00060 inline bool testAndSetOrdered(int expectedValue, int newValue) 00061 { 00062 mutexlocker lock(&m); 00063 if (_q_value == expectedValue) { 00064 _q_value = newValue; 00065 return true; 00066 } 00067 return false; 00068 } 00069 00070 // Non-atomic API 00071 inline bool operator==(int value) const 00072 { 00073 return _q_value == value; 00074 } 00075 00076 inline bool operator!=(int value) const 00077 { 00078 return _q_value != value; 00079 } 00080 00081 inline bool operator!() const 00082 { 00083 return _q_value == 0; 00084 } 00085 00086 inline operator int() const 00087 { 00088 return _q_value; 00089 } 00090 00091 inline atomicInt &operator=(int value) 00092 { 00093 _q_value = value; 00094 return *this; 00095 } 00096 00097 inline bool operator>(int value) const 00098 { 00099 return _q_value > value; 00100 } 00101 00102 inline bool operator<(int value) const 00103 { 00104 return _q_value < value; 00105 } 00106 00107 private: 00108 volatile int _q_value; 00109 mutex m; 00110 }; 00111 00112 }//namespace 00113 00114 #endif 00115