-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpool.go
More file actions
72 lines (61 loc) · 1.01 KB
/
pool.go
File metadata and controls
72 lines (61 loc) · 1.01 KB
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_utils
import (
"fmt"
"runtime"
"sync"
)
type PoolFunc func()
type easyPool struct {
limit chan struct{}
pool chan PoolFunc
close PoolFunc
}
func NewPoolFunc(size int, close PoolFunc) *easyPool {
pool := &easyPool{
limit: make(chan struct{}, size),
pool: make(chan PoolFunc, size),
close: close,
}
go pool.core()
return pool
}
func (e *easyPool) Send(fn PoolFunc) {
e.pool <- fn
}
func (e *easyPool) Over() {
close(e.pool)
}
func (e *easyPool) core() {
wg := sync.WaitGroup{}
loop:
for {
select {
case fn, over := <-e.pool:
if !over {
break loop
}
e.limit <- struct{}{}
wg.Add(1)
go func(fn PoolFunc) {
defer func() {
if err := recover(); err != nil {
PrintStack()
fmt.Println("Recover Err: ", err)
}
}()
defer func() {
<-e.limit
wg.Done()
}()
fn()
}(fn)
}
}
wg.Wait()
e.close()
}
func PrintStack() {
var buf [4096]byte
n := runtime.Stack(buf[:], false)
fmt.Printf("GO ==> %s\n", string(buf[:n]))
}