-
Notifications
You must be signed in to change notification settings - Fork 15
/
mux.go
303 lines (261 loc) · 5.86 KB
/
mux.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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
package dingo
//
// 'mux' is a n-to-1 multiplexer for a slice of 'receiving' channels.
// Users can add handler function to handle those input values.
//
// the original use case in 'dingo' is muxing from chan<-task.TaskInfo from
// brokers and chan<-task.Report from backends.
//
// 'mux' won't close those registered channels, but it would take care of
// its output channel, callers should check channel validity when receiving
// from 'mux''s output channel:
//
// m := &mux{}
// m.Init()
// ...
// m.Handle(func(v interface{}, idx int) {
// // output it to another channel
// out <- v.(string)
// })
//
import (
"fmt"
"math/rand"
"reflect"
"sort"
"sync"
"sync/atomic"
"time"
)
type _newChannel struct {
id int
v interface{}
}
type mux struct {
rs *Routines
changed []chan time.Time
rsLock sync.Mutex
// check for new condition
cases atomic.Value
casesLock sync.Mutex
handlersLock sync.Mutex
handlers atomic.Value
}
func newMux() (m *mux) {
m = &mux{
rs: NewRoutines(),
changed: make([]chan time.Time, 0, 10),
}
m.cases.Store(make(map[int]interface{}))
m.handlers.Store(make([]func(interface{}, int), 0, 10))
return
}
//
func (mx *mux) More(count int) (remain int, err error) {
remain = count
for ; remain > 0; remain-- {
c := make(chan time.Time, 10)
mx.changed = append(mx.changed, c)
go mx.muxRoutine(mx.rs.New(), mx.rs.Wait(), c)
}
return
}
//
func (mx *mux) Close() {
func() {
mx.rsLock.Lock()
defer mx.rsLock.Unlock()
mx.rs.Close()
for _, v := range mx.changed {
close(v)
}
mx.changed = make([]chan time.Time, 0, 10)
}()
mx.casesLock.Lock()
defer mx.casesLock.Unlock()
mx.cases.Store(make(map[int]interface{}))
mx.handlersLock.Lock()
defer mx.handlersLock.Unlock()
mx.handlers.Store(make([]func(interface{}, int), 0, 10))
}
//
func (mx *mux) Register(ch interface{}, expectedID int) (id int, err error) {
func() {
mx.casesLock.Lock()
defer mx.casesLock.Unlock()
m := mx.cases.Load().(map[int]interface{})
id = expectedID
for {
if _, ok := m[id]; !ok {
break
}
id = rand.Int()
}
nm := make(map[int]interface{})
for k := range m {
nm[k] = m[k]
}
nm[id] = ch
mx.cases.Store(nm)
}()
mx.rsLock.Lock()
defer mx.rsLock.Unlock()
touched := time.Now()
for _, v := range mx.changed {
v <- touched
}
return
}
//
func (mx *mux) Unregister(id int) (ch interface{}, err error) {
func() {
mx.casesLock.Lock()
defer mx.casesLock.Unlock()
var ok bool
m := mx.cases.Load().(map[int]interface{})
if ch, ok = m[id]; !ok {
err = fmt.Errorf("Id not found:%v", id)
return
}
nm := make(map[int]interface{})
for k := range m {
nm[k] = m[k]
}
delete(nm, id)
mx.cases.Store(nm)
}()
mx.rsLock.Lock()
defer mx.rsLock.Unlock()
touched := time.Now()
for _, v := range mx.changed {
v <- touched
}
return
}
func (mx *mux) Handle(handler func(interface{}, int)) {
mx.handlersLock.Lock()
defer mx.handlersLock.Unlock()
m := mx.handlers.Load().([]func(interface{}, int))
nm := make([]func(interface{}, int), 0, len(m)+1)
copy(nm, m)
nm = append(nm, handler)
mx.handlers.Store(nm)
}
func (mx *mux) muxRoutine(quit <-chan int, wait *sync.WaitGroup, changed <-chan time.Time) {
defer wait.Done()
var (
cond []reflect.SelectCase
handlers []func(interface{}, int)
keys []int
lenOfcases int
)
del := func(chosen int) {
cond = append(cond[:chosen], cond[chosen+1:]...)
keys = append(keys[:chosen], keys[chosen+1:]...)
lenOfcases--
}
update := func() {
m := mx.cases.Load().(map[int]interface{})
keys = make([]int, 0, 10)
for k := range m {
keys = append(keys, k)
}
sort.Ints(keys)
cond = make([]reflect.SelectCase, 0, 10)
for _, k := range keys {
cond = append(cond, reflect.SelectCase{
Dir: reflect.SelectRecv,
Chan: reflect.ValueOf(m[k]),
})
}
// add quit channel
cond = append(cond, reflect.SelectCase{
Dir: reflect.SelectRecv,
Chan: reflect.ValueOf(quit),
})
// add changed channel
cond = append(cond, reflect.SelectCase{
Dir: reflect.SelectRecv,
Chan: reflect.ValueOf(changed),
})
lenOfcases = len(m)
}
update()
for {
chosen, value, ok := reflect.Select(cond)
if !ok {
// control channel is closed (quit, changed)
if chosen >= lenOfcases {
goto cleanup
}
// remove that channel
del(chosen)
// its value is not trustable,
// so go for another round of for loop.
continue
}
switch chosen {
// quit channel is triggered.
case lenOfcases:
goto cleanup
// changed channel is triggered
case lenOfcases + 1:
// clear remaining changed event
cleared := false
for {
select {
case <-changed:
default:
cleared = true
}
if cleared {
break
}
}
update()
// other registered channels
default:
// send to handlers
handlers = mx.handlers.Load().([]func(interface{}, int))
for _, v := range handlers {
v(value.Interface(), keys[chosen])
}
}
}
cleanup:
// update for the last time
update()
cond = cond[:len(cond)-2] // pop quit, changed channel
cond = append(cond, reflect.SelectCase{
Dir: reflect.SelectDefault,
}) // append a default case
// consuming things remaining in channels,
// until cleared.
finished:
for {
chosen, value, ok := reflect.Select(cond)
// note: when default case is triggered,
// 'ok' is always false, which is meaningless.
if !ok && chosen < lenOfcases {
// remove that channel
del(chosen)
continue
}
switch chosen {
// default is triggered
case len(cond) - 1:
break finished
default:
handlers = mx.handlers.Load().([]func(interface{}, int))
for _, v := range handlers {
if chosen >= len(keys) {
panic(fmt.Sprintf("chosen is larger than length of keys: %v %v", chosen, keys))
}
v(value.Interface(), keys[chosen])
}
}
}
}
func init() {
rand.Seed(time.Now().UnixNano())
}