/
pool.go
75 lines (70 loc) · 1.5 KB
/
pool.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
package koncurrent
import (
"context"
"github.com/opentracing/opentracing-go"
"runtime/debug"
)
type PoolExecutor struct {
queue chan taskContext
}
type taskContext struct {
context.Context
opt TaskExecutionOptions
task TaskFunc
taskId int
resultChn chan TaskResult
}
func (p PoolExecutor) Execute(ctx context.Context, task TaskFunc, taskId int, resultChn chan TaskResult, opt TaskExecutionOptions) {
p.queue <- taskContext{
Context: ctx,
task: task,
taskId: taskId,
resultChn: resultChn,
opt: opt,
}
}
func NewPoolExecutor(poolSize int, queueSize int) PoolExecutor {
ret := PoolExecutor{
queue: make(chan taskContext, queueSize),
}
for i := 0; i < poolSize; i++ {
go func() {
for {
taskCtx := <-ret.queue
ctx := taskCtx.Context
tracingSpanName := taskCtx.opt.tracingSpanName
resultChn := taskCtx.resultChn
taskFunc := taskCtx.task
taskId := taskCtx.taskId
func() {
defer func() {
if r := recover(); r != nil {
resultChn <- TaskResult{
err: PanicError{
Stack: debug.Stack(),
},
id: taskId,
}
}
}()
var s opentracing.Span
c := ctx
if len(tracingSpanName) > 0 {
span, spanCtx := opentracing.StartSpanFromContext(ctx, tracingSpanName)
s = span
c = spanCtx
}
taskErr := taskFunc(c)
resultChn <- TaskResult{
err: taskErr,
id: taskId,
}
if s != nil {
s.Finish()
}
}()
}
}()
}
return ret
}