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