atomicCounter.h
Go to the documentation of this file.
/* atomicCounter.h
*/
#ifndef OSL_ATOMICCOUNTER_H
#define OSL_ATOMICCOUNTER_H
#include "osl/config.h"
#include <atomic>
#include <algorithm>
namespace osl
{
namespace misc
{
template <class Counter>
struct IncrementLock
{
Counter& counter;
explicit IncrementLock(Counter& c) : counter(c)
{
counter.inc();
}
~IncrementLock()
{
counter.dec();
}
IncrementLock(const IncrementLock&) = delete;
IncrementLock& operator=(const IncrementLock&) = delete;
};
class AtomicCounter
{
std::atomic<int> count;
public:
explicit AtomicCounter(int count_=0) {
this->count=count_;
}
void inc(){
count.fetch_add(1);
}
void inc(int value){
count.fetch_add(value);
}
int valueAndinc(){
return count.fetch_add(1);
}
void dec(){
count.fetch_sub(1);
}
void max(int val){
int x=count;
if(x<val){
while(! count.compare_exchange_weak(x,val) && x<val)
;
}
}
int value() const{
return count;
}
void setValue(int value) {
count = value;
}
typedef IncrementLock<AtomicCounter> IncLock;
};
}
using misc::AtomicCounter;
}
#endif /* OSL_ATOMICCOUNTER_H */
// ;;; Local Variables:
// ;;; mode:c++
// ;;; c-basic-offset:2
// ;;; End:
osl::AtomicCounter::AtomicCounter
AtomicCounter(int count_=0)
Definition atomicCounter.h:33
osl::misc::AtomicCounter
Definition atomicCounter.h:30
osl::misc::AtomicCounter::inc
void inc()
Definition atomicCounter.h:36
osl::misc::AtomicCounter::count
std::atomic< int > count
Definition atomicCounter.h:31
osl::misc::AtomicCounter::valueAndinc
int valueAndinc()
Definition atomicCounter.h:42
osl::misc::AtomicCounter::dec
void dec()
Definition atomicCounter.h:45
osl::misc::AtomicCounter::inc
void inc(int value)
Definition atomicCounter.h:39
osl::misc::AtomicCounter::setValue
void setValue(int value)
Definition atomicCounter.h:58
osl::misc::AtomicCounter::IncLock
IncrementLock< AtomicCounter > IncLock
Definition atomicCounter.h:61
osl::misc::AtomicCounter::max
void max(int val)
Definition atomicCounter.h:48
osl::misc::AtomicCounter::value
int value() const
Definition atomicCounter.h:55
osl::misc::AtomicCounter::AtomicCounter
AtomicCounter(int count_=0)
Definition atomicCounter.h:33
config.h
osl::misc
Definition basic_type.h:66
osl
Definition additionalEffect.h:6
osl::misc::IncrementLock
Definition atomicCounter.h:16
osl::misc::IncrementLock< AtomicCounter >::counter
AtomicCounter & counter
Definition atomicCounter.h:17
osl::misc::IncrementLock::IncrementLock
IncrementLock(const IncrementLock &)=delete
osl::misc::IncrementLock::operator=
IncrementLock & operator=(const IncrementLock &)=delete
osl::misc::IncrementLock::~IncrementLock
~IncrementLock()
Definition atomicCounter.h:22
osl::misc::IncrementLock::IncrementLock
IncrementLock(Counter &c)
Definition atomicCounter.h:18