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