1#include "../Mutex.h"
2using muduo::MutexLock;
3using muduo::MutexLockGuard;
4
5// A thread-safe counter
6class Counter : boost::noncopyable
7{
8  // copy-ctor and assignment should be private by default for a class.
9 public:
10  Counter() : value_(0) {}
11  Counter& operator=(const Counter& rhs);
12
13  int64_t value() const;
14  int64_t getAndIncrease();
15
16  friend void swap(Counter& a, Counter& b);
17
18 private:
19  mutable MutexLock mutex_;
20  int64_t value_;
21};
22
23int64_t Counter::value() const
24{
25  MutexLockGuard lock(mutex_);
26  return value_;
27}
28
29int64_t Counter::getAndIncrease()
30{
31  MutexLockGuard lock(mutex_);
32  int64_t ret = value_++;
33  return ret;
34}
35
36void swap(Counter& a, Counter& b)
37{
38  MutexLockGuard aLock(a.mutex_);  // potential dead lock
39  MutexLockGuard bLock(b.mutex_);
40  int64_t value = a.value_;
41  a.value_ = b.value_;
42  b.value_ = value;
43}
44
45Counter& Counter::operator=(const Counter& rhs)
46{
47  if (this == &rhs)
48    return *this;
49
50  MutexLockGuard myLock(mutex_);  // potential dead lock
51  MutexLockGuard itsLock(rhs.mutex_);
52  value_ = rhs.value_;
53  return *this;
54}
55
56int main()
57{
58  Counter c;
59  c.getAndIncrease();
60}
61