forked from dean2020/hackpool
-
Notifications
You must be signed in to change notification settings - Fork 5
/
reshackpool.go
59 lines (49 loc) · 1001 Bytes
/
reshackpool.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
package hackpool
import "sync"
type ResHackPool struct {
numGo int
messages chan arg
function func(...interface{}) interface{}
}
type Result struct {
ID int
Tag string
Value interface{}
}
type arg struct {
ID int
Tag string
Data []interface{}
}
func NewRes(numGoroutine int, function func(...interface{}) interface{}) *ResHackPool {
return &ResHackPool{
numGo: numGoroutine,
messages: make(chan arg),
function: function,
}
}
func (c *ResHackPool) Push(id int, tag string, data ...interface{}) {
c.messages <- arg{ID: id, Tag: tag, Data: data}
}
func (c *ResHackPool) CloseQueue() {
close(c.messages)
}
func (c *ResHackPool) Run() <-chan Result {
var wg sync.WaitGroup
rc := make(chan Result)
wg.Add(c.numGo)
for i := 0; i < c.numGo; i++ {
go func() {
for arg := range c.messages {
r := c.function(arg.Data...)
rc <- Result{ID: arg.ID, Tag: arg.Tag, Value: r}
}
wg.Done()
}()
}
go func() {
wg.Wait()
close(rc)
}()
return rc
}