-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparallel.go
82 lines (69 loc) · 2 KB
/
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
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
package rheos
import (
"context"
"golang.org/x/sync/errgroup"
)
// ParFilterMap is like FilterMap, but runs the mapping and filtering operations concurrently with num goroutines.
// The order of the output elements is undefined.
// It's better to use it with a buffered stream.
func ParFilterMap[I any, O any](pipe Stream[I], num int, callback func(context.Context, I) (O, bool, error), ops ...Option[O]) Stream[O] {
output := make(chan O)
for _, op := range ops {
output = op()
}
eg, ctx := errgroup.WithContext(pipe.ctx)
pipe.eg.Go(func() error { // goroutine which spawns more goroutines
defer close(output)
for i := 0; i < num; i++ {
eg.Go(func() error {
for elem := range pipe.in {
mapped, ok, err := callback(ctx, elem)
if err != nil {
return err
}
if !ok {
continue
}
if err := push(ctx, output, mapped); err != nil {
return err
}
}
return nil
})
}
return eg.Wait()
})
return Stream[O]{
in: output,
eg: pipe.eg,
ctx: pipe.ctx,
}
}
// ParMap is like Map, but runs the mapping operations concurrently with num goroutines.
// The order of the output elements is undefined.
// It's better to use it with a buffered stream.
func ParMap[I any, O any](pipe Stream[I], num int, mapper func(context.Context, I) (O, error), ops ...Option[O]) Stream[O] {
return ParFilterMap[I, O](
pipe,
num,
func(ctx context.Context, elem I) (O, bool, error) {
mapped, err := mapper(ctx, elem)
return mapped, true, err
},
ops...,
)
}
// ParFilter is like Filter, but runs the filtering operations concurrently with num goroutines.
// The order of the output elements is undefined.
// It's better to use it with a buffered stream.
func ParFilter[I any](pipe Stream[I], num int, callback func(context.Context, I) (bool, error), ops ...Option[I]) Stream[I] {
return ParFilterMap[I, I](
pipe,
num,
func(ctx context.Context, elem I) (I, bool, error) {
ok, err := callback(ctx, elem)
return elem, ok, err
},
ops...,
)
}