-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathatomic_int.h
64 lines (47 loc) · 1.23 KB
/
atomic_int.h
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
/*
* atomic_int.h
*
* Created on: 2011-10-14
* Author: gxl2007@hotmail.com
*/
#ifndef ATOMIC_INT_H_
#define ATOMIC_INT_H_
#include <stdint.h>
namespace xlnet
{
template<typename T>
class atomic_int
{
public:
typedef T int_type ;
atomic_int():m_counter(0) { } ;
~atomic_int() { } ;
/*
* brief atomically read value
*/
int_type get() { return m_counter ; } ;
/*
* @brief atomically set value
*/
int_type set(int_type v) { m_counter = v ; } ;
/**
* @brief atomically add a value and return new value
* @param [in]: integer value to add
* @return new value
*/
int_type add(int_type i) { return __sync_add_and_fetch(&m_counter,i) ; } ;
/**
* @brief atomically sub a value and return new value
* @param [in]: integer value to sub
* @return new value
*/
int_type sub(int_type i) { return __sync_sub_and_fetch(&m_counter,i) ; } ;
private:
volatile int_type m_counter ;
};
typedef atomic_int<int8_t> atomic_int8 ;
typedef atomic_int<int16_t> atomic_int16 ;
typedef atomic_int<int32_t> atomic_int32 ;
typedef atomic_int<int64_t> atomic_int64 ;
}
#endif /* ATOMIC_INT_H_ */