-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.go
85 lines (72 loc) · 1.52 KB
/
util.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
76
77
78
79
80
81
82
83
package alloter
import (
"context"
"fmt"
"runtime/debug"
"sync"
)
type BaseActuator interface {
Exec(tasks *[]Task) error
ExecWithContext(ctx context.Context, tasks *[]Task) error
}
type TimedAlloter interface {
BaseActuator
}
type Task func() error
// wrapperTask will wrapper the task in order to notice execution result
// to the main process
func wrapperTask(ctx context.Context, task Task, wg *sync.WaitGroup, resChan *chan error, errChan *chan error) func() {
return func() {
defer func() {
if r := recover(); r != nil {
err := fmt.Errorf("alloter panic:%v\n%s", r, string(debug.Stack()))
*errChan <- err
}
wg.Done()
}()
select {
case <-ctx.Done():
case *resChan <- task():
err := <- *resChan
if err != nil {
*errChan <- err
}
}
}
}
func wrapperSimpleTask(task Task, wg *sync.WaitGroup, resChan *chan error) func() {
return func() {
defer func() {
if r := recover(); r != nil {
err := fmt.Errorf("alloter panic:%v\n%s", r, string(debug.Stack()))
*resChan <- err
}
wg.Done()
}()
err := task()
if err != nil {
*resChan <- err
}
}
}
func noBlockGo (ctx context.Context, errChan *chan error) (end bool, err error) {
select {
case <-ctx.Done():
return true, ctx.Err()
case err = <-*errChan:
return true, err
default:
}
return false, nil
}
func blockGo (ctx context.Context, errChan *chan error) (err error) {
select {
case <-ctx.Done():
if ctx.Err() != context.Canceled {
return ctx.Err()
}
case err = <-*errChan:
return err
}
return nil
}