1// excerpts from http://code.google.com/p/muduo/ 2// 3// Use of this source code is governed by a BSD-style license 4// that can be found in the License file. 5// 6// Author: Shuo Chen (giantchen at gmail dot com) 7 8#ifndef MUDUO_BASE_ATOMIC_H 9#define MUDUO_BASE_ATOMIC_H 10 11#include <boost/noncopyable.hpp> 12#include <stdint.h> 13 14namespace muduo 15{ 16 17namespace detail 18{ 19template<typename T> 20class AtomicIntegerT : boost::noncopyable 21{ 22 public: 23 AtomicIntegerT() 24 : value_(0) 25 { 26 } 27 28 // uncomment if you need copying and assignment 29 // 30 // AtomicIntegerT(const AtomicIntegerT& that) 31 // : value_(that.get()) 32 // {} 33 // 34 // AtomicIntegerT& operator=(const AtomicIntegerT& that) 35 // { 36 // getAndSet(that.get()); 37 // return *this; 38 // } 39 40 T get() const 41 { 42 return __sync_val_compare_and_swap(const_cast<volatile T*>(&value_), 0, 0); 43 } 44 45 T getAndAdd(T x) 46 { 47 return __sync_fetch_and_add(&value_, x); 48 } 49 50 T addAndGet(T x) 51 { 52 return getAndAdd(x) + x; 53 } 54 55 T incrementAndGet() 56 { 57 return addAndGet(1); 58 } 59 60 void add(T x) 61 { 62 getAndAdd(x); 63 } 64 65 void increment() 66 { 67 incrementAndGet(); 68 } 69 70 void decrement() 71 { 72 getAndAdd(-1); 73 } 74 75 T getAndSet(T newValue) 76 { 77 return __sync_lock_test_and_set(&value_, newValue); 78 } 79 80 private: 81 volatile T value_; 82}; 83} 84 85typedef detail::AtomicIntegerT<int32_t> AtomicInt32; 86typedef detail::AtomicIntegerT<int64_t> AtomicInt64; 87} 88 89#endif // MUDUO_BASE_ATOMIC_H 90