Atomic.h revision cd139dc7
1cd139dc7SShuo Chen// excerpts from http://code.google.com/p/muduo/ 2cd139dc7SShuo Chen// 3cd139dc7SShuo Chen// Use of this source code is governed by a BSD-style license 4cd139dc7SShuo Chen// that can be found in the License file. 5cd139dc7SShuo Chen// 6cd139dc7SShuo Chen// Author: Shuo Chen (giantchen at gmail dot com) 7cd139dc7SShuo Chen 8cd139dc7SShuo Chen#ifndef MUDUO_BASE_ATOMIC_H 9cd139dc7SShuo Chen#define MUDUO_BASE_ATOMIC_H 10cd139dc7SShuo Chen 11cd139dc7SShuo Chen#include <boost/noncopyable.hpp> 12cd139dc7SShuo Chen#include <stdint.h> 13cd139dc7SShuo Chen 14cd139dc7SShuo Chennamespace muduo 15cd139dc7SShuo Chen{ 16cd139dc7SShuo Chen 17cd139dc7SShuo Chennamespace detail 18cd139dc7SShuo Chen{ 19cd139dc7SShuo Chentemplate<typename T> 20cd139dc7SShuo Chenclass AtomicIntegerT : boost::noncopyable 21cd139dc7SShuo Chen{ 22cd139dc7SShuo Chen public: 23cd139dc7SShuo Chen AtomicIntegerT() 24cd139dc7SShuo Chen : value_(0) 25cd139dc7SShuo Chen { 26cd139dc7SShuo Chen } 27cd139dc7SShuo Chen 28cd139dc7SShuo Chen T get() const 29cd139dc7SShuo Chen { 30cd139dc7SShuo Chen return value_; 31cd139dc7SShuo Chen } 32cd139dc7SShuo Chen 33cd139dc7SShuo Chen T getAndAdd(T x) 34cd139dc7SShuo Chen { 35cd139dc7SShuo Chen return __sync_fetch_and_add(&value_, x); 36cd139dc7SShuo Chen } 37cd139dc7SShuo Chen 38cd139dc7SShuo Chen T addAndGet(T x) 39cd139dc7SShuo Chen { 40cd139dc7SShuo Chen return getAndAdd(x) + x; 41cd139dc7SShuo Chen } 42cd139dc7SShuo Chen 43cd139dc7SShuo Chen T incrementAndGet() 44cd139dc7SShuo Chen { 45cd139dc7SShuo Chen return addAndGet(1); 46cd139dc7SShuo Chen } 47cd139dc7SShuo Chen 48cd139dc7SShuo Chen void increment() 49cd139dc7SShuo Chen { 50cd139dc7SShuo Chen incrementAndGet(); 51cd139dc7SShuo Chen } 52cd139dc7SShuo Chen 53cd139dc7SShuo Chen void decrement() 54cd139dc7SShuo Chen { 55cd139dc7SShuo Chen getAndAdd(-1); 56cd139dc7SShuo Chen } 57cd139dc7SShuo Chen 58cd139dc7SShuo Chen T getAndSet(T newValue) 59cd139dc7SShuo Chen { 60cd139dc7SShuo Chen return __sync_lock_test_and_set(&value_, newValue); 61cd139dc7SShuo Chen } 62cd139dc7SShuo Chen 63cd139dc7SShuo Chen private: 64cd139dc7SShuo Chen volatile T value_; 65cd139dc7SShuo Chen}; 66cd139dc7SShuo Chen} 67cd139dc7SShuo Chen 68cd139dc7SShuo Chentypedef detail::AtomicIntegerT<int32_t> AtomicInt32; 69cd139dc7SShuo Chentypedef detail::AtomicIntegerT<int64_t> AtomicInt64; 70cd139dc7SShuo Chen} 71cd139dc7SShuo Chen 72cd139dc7SShuo Chen#endif // MUDUO_BASE_ATOMIC_H 73