atomicCounter.h Source File

- Main Page
- Namespaces
- Classes
- Files

- File List
- File Members

All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros
atomicCounter.h
Go to the documentation of this file.
1 /* atomicCounter.h
2 */
3 #ifndef OSL_ATOMICCOUNTER_H
4 #define OSL_ATOMICCOUNTER_H
5
6 #include "osl/config.h"
7 #ifdef USE_TBB_ATOMIC
8 # include <tbb/atomic.h>
9 #else
10 # include "osl/misc/lightMutex.h"
11 #endif
12 #include <algorithm>
13
14 namespace osl
15 {
16 namespace misc
17 {
18 template <class Counter>
19 struct IncrementLock
20 {
21 Counter& counter;
22 explicit IncrementLock(Counter& c) : counter(c)
23 {
24 counter.inc();
25 }
26 ~IncrementLock()
27 {
28 counter.dec();
29 }
30 };
31 #ifdef USE_TBB_ATOMIC
32 class AtomicCounter
33 {
34 tbb::atomic<int> count;
35 public:
36 explicit AtomicCounter(int count_=0) {
37 this->count=count_;
38 }
39 void inc(){
40 count.fetch_and_increment();
41 }
42 void inc(int value){
43 count.fetch_and_add(value);
44 }
45 int valueAndinc(){
46 return count.fetch_and_increment();
47 }
48 void dec(){
49 count.fetch_and_decrement();
50 }
51 void max(int val){
52 int x=count;
53 if(x<val){
54 int oldx;
55 while((oldx=count.compare_and_swap(val,x))!=x){
56 x=oldx;
57 if(x>=val) break;
58 }
59 }
60 }
61 int value() const{
62 return count;
63 }
64 void setValue(int value) {
65 count = value;
66 }
67 typedef IncrementLock<AtomicCounter> IncLock;
68 };
69 #else
70 class AtomicCounter
71 {
72 typedef LightMutex Mutex;
73 mutable Mutex m;
74 int count;
75 public:
76 explicit AtomicCounter(int count=0) :count(count){}
77 void inc(){
78 SCOPED_LOCK(lk,m);
79 count++;
80 }
81 int valueAndinc(){
82 SCOPED_LOCK(lk,m);
83 return count++;
84 }
85 void dec(){
86 SCOPED_LOCK(lk,m);
87 count--;
88 }
89 void max(int val){
90 SCOPED_LOCK(lk,m);
91 count=std::max(count,val);
92 }
93 int value() const{
94 SCOPED_LOCK(lk,m);
95 return count;
96 }
97 void setValue(int value) {
98 SCOPED_LOCK(lk,m);
99 count = value;
100 }
101 typedef IncrementLock<AtomicCounter> IncLock;
102 };
103 #endif
104 }
105 using misc::AtomicCounter;
106 }
107
108 #endif /* OSL_ATOMICCOUNTER_H */
109 // ;;; Local Variables:
110 // ;;; mode:c++
111 // ;;; c-basic-offset:2
112 // ;;; End:
113