Counter.cc revision 1bc80516
11bc80516SShuo Chen#include "../Mutex.h" 21bc80516SShuo Chenusing muduo::MutexLock; 31bc80516SShuo Chenusing muduo::MutexLockGuard; 41bc80516SShuo Chen 51bc80516SShuo Chen// A thread-safe counter 61bc80516SShuo Chenclass Counter : boost::noncopyable 71bc80516SShuo Chen{ 81bc80516SShuo Chen // copy-ctor and assignment should be private by default for a class. 91bc80516SShuo Chen public: 101bc80516SShuo Chen Counter() : value_(0) {} 111bc80516SShuo Chen Counter& operator=(const Counter& rhs); 121bc80516SShuo Chen 131bc80516SShuo Chen int64_t value() const; 141bc80516SShuo Chen int64_t getAndIncrease(); 151bc80516SShuo Chen 161bc80516SShuo Chen friend void swap(Counter& a, Counter& b); 171bc80516SShuo Chen 181bc80516SShuo Chen private: 191bc80516SShuo Chen mutable MutexLock mutex_; 201bc80516SShuo Chen int64_t value_; 211bc80516SShuo Chen}; 221bc80516SShuo Chen 231bc80516SShuo Chenint64_t Counter::value() const 241bc80516SShuo Chen{ 251bc80516SShuo Chen MutexLockGuard lock(mutex_); 261bc80516SShuo Chen return value_; 271bc80516SShuo Chen} 281bc80516SShuo Chen 291bc80516SShuo Chenint64_t Counter::getAndIncrease() 301bc80516SShuo Chen{ 311bc80516SShuo Chen MutexLockGuard lock(mutex_); 321bc80516SShuo Chen int64_t ret = value_++; 331bc80516SShuo Chen return ret; 341bc80516SShuo Chen} 351bc80516SShuo Chen 361bc80516SShuo Chenvoid swap(Counter& a, Counter& b) 371bc80516SShuo Chen{ 381bc80516SShuo Chen MutexLockGuard aLock(a.mutex_); // potential dead lock 391bc80516SShuo Chen MutexLockGuard bLock(b.mutex_); 401bc80516SShuo Chen int64_t value = a.value_; 411bc80516SShuo Chen a.value_ = b.value_; 421bc80516SShuo Chen b.value_ = value; 431bc80516SShuo Chen} 441bc80516SShuo Chen 451bc80516SShuo ChenCounter& Counter::operator=(const Counter& rhs) 461bc80516SShuo Chen{ 471bc80516SShuo Chen if (this == &rhs) 481bc80516SShuo Chen return *this; 491bc80516SShuo Chen 501bc80516SShuo Chen MutexLockGuard myLock(mutex_); // potential dead lock 511bc80516SShuo Chen MutexLockGuard itsLock(rhs.mutex_); 521bc80516SShuo Chen value_ = rhs.value_; 531bc80516SShuo Chen return *this; 541bc80516SShuo Chen} 551bc80516SShuo Chen 561bc80516SShuo Chenint main() 571bc80516SShuo Chen{ 581bc80516SShuo Chen Counter c; 591bc80516SShuo Chen c.getAndIncrease(); 601bc80516SShuo Chen} 61