-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathring.go
85 lines (73 loc) · 1.33 KB
/
ring.go
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
package main
import (
"errors"
"intoyun-enterprise-demo-go/libs/proto"
log "github.com/thinkboy/log4go"
)
var (
ErrRingEmpty = errors.New("ring buffer empty")
ErrRingFull = errors.New("ring buffer full")
)
type Ring struct {
// read
rp uint64
num uint64
mask uint64
// TODO split cacheline, many cpu cache line size is 64
// pad [40]byte
// write
wp uint64
data []proto.Proto
}
func NewRing(num int) *Ring {
r := new(Ring)
r.init(uint64(num))
return r
}
func (r *Ring) Init(num int) {
r.init(uint64(num))
}
func (r *Ring) init(num uint64) {
// 2^N
if num&(num-1) != 0 {
for num&(num-1) != 0 {
num &= (num - 1)
}
num = num << 1
}
r.data = make([]proto.Proto, num)
r.num = num
r.mask = r.num - 1
}
func (r *Ring) Get() (proto *proto.Proto, err error) {
if r.rp == r.wp {
return nil, ErrRingEmpty
}
proto = &r.data[r.rp&r.mask]
return
}
func (r *Ring) GetAdv() {
r.rp++
if Debug {
log.Debug("ring rp: %d, idx: %d", r.rp, r.rp&r.mask)
}
}
func (r *Ring) Set() (proto *proto.Proto, err error) {
if r.wp-r.rp >= r.num {
return nil, ErrRingFull
}
proto = &r.data[r.wp&r.mask]
return
}
func (r *Ring) SetAdv() {
r.wp++
if Debug {
log.Debug("ring wp: %d, idx: %d", r.wp, r.wp&r.mask)
}
}
func (r *Ring) Reset() {
r.rp = 0
r.wp = 0
// prevent pad compiler optimization
// r.pad = [40]byte{}
}