forked from gptscript-ai/gptscript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparallel.go
57 lines (46 loc) · 926 Bytes
/
parallel.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
package runner
import (
"context"
"golang.org/x/sync/errgroup"
)
type dispatcher interface {
Run(func(context.Context) error)
Wait() error
}
type serialDispatcher struct {
ctx context.Context
err error
}
func newSerialDispatcher(ctx context.Context) *serialDispatcher {
return &serialDispatcher{
ctx: ctx,
}
}
func (s *serialDispatcher) Run(f func(context.Context) error) {
if s.err != nil {
return
}
s.err = f(s.ctx)
}
func (s *serialDispatcher) Wait() error {
return s.err
}
type parallelDispatcher struct {
ctx context.Context
eg *errgroup.Group
}
func newParallelDispatcher(ctx context.Context) *parallelDispatcher {
eg, ctx := errgroup.WithContext(ctx)
return ¶llelDispatcher{
ctx: ctx,
eg: eg,
}
}
func (p *parallelDispatcher) Run(f func(context.Context) error) {
p.eg.Go(func() error {
return f(p.ctx)
})
}
func (p *parallelDispatcher) Wait() error {
return p.eg.Wait()
}