00001 /* atomicCounter.h 00002 */ 00003 #ifndef OSL_ATOMICCOUNTER_H 00004 #define OSL_ATOMICCOUNTER_H 00005 00006 #include "osl/config.h" 00007 #include <atomic> 00008 #include <algorithm> 00009 00010 namespace osl 00011 { 00012 namespace misc 00013 { 00014 template <class Counter> 00015 struct IncrementLock 00016 { 00017 Counter& counter; 00018 explicit IncrementLock(Counter& c) : counter(c) 00019 { 00020 counter.inc(); 00021 } 00022 ~IncrementLock() 00023 { 00024 counter.dec(); 00025 } 00026 IncrementLock(const IncrementLock&) = delete; 00027 IncrementLock& operator=(const IncrementLock&) = delete; 00028 }; 00029 class AtomicCounter 00030 { 00031 std::atomic<int> count; 00032 public: 00033 explicit AtomicCounter(int count_=0) { 00034 this->count=count_; 00035 } 00036 void inc(){ 00037 count.fetch_add(1); 00038 } 00039 void inc(int value){ 00040 count.fetch_add(value); 00041 } 00042 int valueAndinc(){ 00043 return count.fetch_add(1); 00044 } 00045 void dec(){ 00046 count.fetch_sub(1); 00047 } 00048 void max(int val){ 00049 int x=count; 00050 if(x<val){ 00051 while(! count.compare_exchange_weak(x,val) && x<val) 00052 ; 00053 } 00054 } 00055 int value() const{ 00056 return count; 00057 } 00058 void setValue(int value) { 00059 count = value; 00060 } 00061 typedef IncrementLock<AtomicCounter> IncLock; 00062 }; 00063 } 00064 using misc::AtomicCounter; 00065 } 00066 00067 #endif /* OSL_ATOMICCOUNTER_H */ 00068 // ;;; Local Variables: 00069 // ;;; mode:c++ 00070 // ;;; c-basic-offset:2 00071 // ;;; End: 00072