-
Notifications
You must be signed in to change notification settings - Fork 16
/
taskpool.go
74 lines (65 loc) · 1.2 KB
/
taskpool.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
package gobatch
import (
"context"
"fmt"
"github.com/panjf2000/ants/v2"
)
type taskPool struct {
pool *ants.Pool
}
func newTaskPool(size int) *taskPool {
pool, _ := ants.NewPool(size)
return &taskPool{
pool: pool,
}
}
// Future get result in future
type Future interface {
Get() (interface{}, error)
}
type futureImpl struct {
ch <-chan interface{}
}
func (f *futureImpl) Get() (interface{}, error) {
result := <-f.ch
err := <-f.ch
if err == nil {
return result, nil
}
e, ok := err.(error)
if ok {
return result, e
}
return result, fmt.Errorf("future get err:%v", err)
}
func (pool *taskPool) Submit(ctx context.Context, task func() (interface{}, error)) Future {
result := make(chan interface{}, 2)
err := pool.pool.Submit(func() {
defer func() {
if err := recover(); err != nil {
//todo log
result <- nil
result <- fmt.Errorf("panic:%v", err)
close(result)
}
}()
val, err := task()
result <- val
result <- err
close(result)
})
if err != nil {
result <- nil
result <- err
close(result)
}
return &futureImpl{
ch: result,
}
}
func (pool *taskPool) Release() {
pool.pool.Release()
}
func (pool *taskPool) SetMaxSize(size int) {
pool.pool.Tune(size)
}