-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbroadcast.go
137 lines (117 loc) · 2.21 KB
/
broadcast.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
package broadcast
import (
"sync"
)
type Broadcast struct {
data []interface{} //TODO: rewrite with type parameter
meta []interface{}
c *sync.Cond
alive bool
lrSize int //size of last round
round int
wIndex int
}
func NewBroadcast(metaNum int) *Broadcast {
return &Broadcast{
alive: true,
//TODO: implement a RWMutex to replace Mutex here!
c: sync.NewCond(&sync.Mutex{}),
meta: make([]interface{}, 0, metaNum),
}
}
func (bd *Broadcast) WriteMeta(meta interface{}) {
bd.c.L.Lock()
defer bd.c.L.Unlock()
if len(bd.meta) < cap(bd.meta) {
bd.meta = append(bd.meta, meta)
}
}
func (bd *Broadcast) Write(p interface{}) {
bd.c.L.Lock()
defer bd.c.L.Unlock()
if len(bd.meta) < cap(bd.meta) {
return
}
if bd.wIndex >= len(bd.data) {
bd.data = append(bd.data, p)
} else {
bd.data[bd.wIndex] = p
}
bd.wIndex++
bd.c.Broadcast()
}
func (bd *Broadcast) Reset() {
bd.c.L.Lock()
bd.lrSize = bd.wIndex
bd.round++
bd.wIndex = 0
bd.c.L.Unlock()
bd.c.Broadcast()
}
func (bd *Broadcast) DisAlive() {
bd.c.L.Lock()
bd.alive = false
bd.c.L.Unlock()
bd.c.Broadcast()
}
type BroadcastReader struct {
rIndex int
mIndex int
bd *Broadcast
round int
}
func NewBroadcastReader(bd *Broadcast) *BroadcastReader {
return &BroadcastReader{
rIndex: 0,
mIndex: 0,
bd: bd,
round: bd.round,
}
}
func (r *BroadcastReader) reset() {
r.rIndex = 0
r.round = r.bd.round
}
func (r *BroadcastReader) Read() (p interface{}, alive bool) {
r.bd.c.L.Lock()
defer r.bd.c.L.Unlock()
for {
if len(r.bd.meta) < cap(r.bd.meta) {
r.bd.c.Wait()
continue
}
alive = r.bd.alive
if r.mIndex < len(r.bd.meta) {
p = r.bd.meta[r.mIndex]
r.mIndex++
return
}
if r.round == r.bd.round-1 {
if r.rIndex < r.bd.wIndex {
//read too slowly, try to reset reader
r.reset()
} else if r.rIndex < r.bd.lrSize {
//normal, do nothing
} else {
r.reset()
}
} else if r.round == r.bd.round {
if r.rIndex < r.bd.wIndex {
//normal, do nothing
} else {
if alive {
r.bd.c.Wait()
continue
} else {
return
}
}
} else {
r.reset()
}
break
}
p = r.bd.data[r.rIndex] //BUG: maybe panic with index 0
r.rIndex++
return p, true
}