-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmerge.go
102 lines (91 loc) · 1.92 KB
/
merge.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
package async
import (
"errors"
"sync"
)
type request struct {
key string
method func() (interface{}, error)
callback chan *reply
}
type reply struct {
key string
result interface{}
err error
}
type Merge struct {
callbackDic map[string][]chan *reply
inputQueue chan *request
outputQueue chan *reply
shutdown chan bool
wg sync.WaitGroup
isDestory bool
destoryOnce sync.Once
}
func NewMerge() *Merge {
m := &Merge{
callbackDic: make(map[string][]chan *reply),
inputQueue: make(chan *request, 128),
outputQueue: make(chan *reply, 16),
shutdown: make(chan bool),
isDestory: false,
}
go m.runloop()
return m
}
func (m *Merge) runloop() {
for {
select {
case <-m.shutdown:
{
return
}
case rep := <-m.outputQueue:
{
target, ok := m.callbackDic[rep.key]
if ok {
for _, callback := range target {
callback <- rep
}
delete(m.callbackDic, rep.key)
}
}
case req := <-m.inputQueue:
{
target, ok := m.callbackDic[req.key]
if ok {
m.callbackDic[req.key] = append(target, req.callback)
} else {
target = make([]chan *reply, 1)
target[0] = req.callback
m.callbackDic[req.key] = target
go func(key string, method func() (interface{}, error)) {
res, err := Safety(method)
m.outputQueue <- &reply{key: key, result: res, err: err}
}(req.key, req.method)
}
}
}
}
}
func (m *Merge) Destory() {
m.destoryOnce.Do(func() {
m.isDestory = true
})
m.wg.Wait()
close(m.shutdown)
close(m.inputQueue)
close(m.outputQueue)
}
func (m *Merge) Exec(key string, method func() (interface{}, error)) (interface{}, error) {
if m.isDestory {
return nil, errors.New("Merge Destoried")
}
m.wg.Add(1)
defer m.wg.Done()
callback := make(chan *reply, 1)
m.inputQueue <- &request{key: key, method: method, callback: callback}
res := <-callback
close(callback)
return res.result, res.err
}