-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathparallel.go
More file actions
141 lines (125 loc) · 2.48 KB
/
parallel.go
File metadata and controls
141 lines (125 loc) · 2.48 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
/**
* @Author: Shi Jinyu
* @Description:
* @File: parallel
* @Version: 1.0.0
* @Date: 2023/4/21 21:57
*/
package go_parallel
import (
"context"
"log"
"sync"
"time"
)
type ParallelProcessor interface {
Do() interface{}
}
type ParallelFunc func() interface{}
func (f ParallelFunc) Do() interface{} {
return f()
}
type processTask struct {
name string
p ParallelProcessor
}
type ProcessResult struct {
Name string
Data interface{}
}
type ParallelObject struct {
ctx context.Context
timeout time.Duration
cancel func()
wg sync.WaitGroup
rch chan ProcessResult
waitCh chan struct{}
endCh chan struct{}
p []processTask
r []ProcessResult
isTimeout bool
}
func NewParallelObject() *ParallelObject {
return &ParallelObject{
ctx: context.Background(),
timeout: 0,
wg: sync.WaitGroup{},
rch: make(chan ProcessResult),
waitCh: make(chan struct{}),
endCh: make(chan struct{}),
p: nil,
r: nil,
}
}
func (p *ParallelObject) SetContext(ctx context.Context) *ParallelObject {
p.ctx, p.cancel = context.WithCancel(ctx)
return p
}
func (p *ParallelObject) SetTimeout(timeout time.Duration) *ParallelObject {
p.timeout = timeout
p.ctx, p.cancel = context.WithTimeout(p.ctx, timeout)
return p
}
func (p *ParallelObject) AppendProcess(name string, f ParallelProcessor) *ParallelObject {
p.p = append(p.p, processTask{
name: name,
p: f,
})
return p
}
func (p *ParallelObject) AppendFunc(name string, f func() interface{}) *ParallelObject {
p.AppendProcess(name, ParallelFunc(f))
return p
}
func (p *ParallelObject) Run() ([]ProcessResult, bool) {
go func() {
defer close(p.endCh)
loop:
for {
select {
case v := <-p.rch:
p.r = append(p.r, v)
case <-p.ctx.Done():
break loop
case <-p.waitCh:
break loop
}
}
p.endCh <- struct{}{}
}()
go func() {
for _, f := range p.p {
p.wg.Add(1)
go func(task processTask) {
defer func() {
if panicErr := recover(); panicErr != nil {
log.Printf("[ERROR]:do sub process panic:%v\n", panicErr)
}
}()
defer p.wg.Done()
in := task.p.Do()
select {
case p.rch <- ProcessResult{
Name: task.name,
Data: in,
}:
case <-p.ctx.Done():
}
}(f)
}
p.wg.Wait()
close(p.waitCh)
close(p.rch)
}()
select {
case <-p.waitCh:
if p.cancel != nil {
p.cancel()
}
p.isTimeout = false
case <-p.ctx.Done():
p.isTimeout = true
}
<-p.endCh
return p.r, p.isTimeout
}