-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasync.go
72 lines (55 loc) · 1008 Bytes
/
async.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
package async
import "sync"
type G interface{}
type Combiner interface {
Add(key, value G)
}
type result struct {
key interface{}
value interface{}
}
type Collector struct {
input chan result
stor Combiner
wg sync.WaitGroup
}
func NewCollector(combiner Combiner) *Collector {
c := &Collector{
input: make(chan result, 100),
stor: combiner,
}
go c.loop()
return c
}
func (c *Collector) Add(op func() (G, G)) {
c.wg.Add(1)
go func() {
key, value := op()
c.input <- result{key, value}
}()
}
func (c *Collector) loop() {
for r := range c.input {
c.stor.Add(r.key, r.value)
c.wg.Done()
}
}
func (c *Collector) Result() G {
c.wg.Wait()
close(c.input)
return c.stor
}
func StringMap() stringMap {
return stringMap{}
}
type stringMap map[string]interface{}
func (sm stringMap) Add(key, value G) {
sm[key.(string)] = value
}
func IntMap() intMap {
return intMap{}
}
type intMap map[int]interface{}
func (im intMap) Add(key, value G) {
im[key.(int)] = value
}