-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapply.go
59 lines (48 loc) · 1.17 KB
/
apply.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
package parallel
import (
"sync"
)
// ApplyChan executes `fn` on each element of `input` channel in multiple threads.
// Options:
//
// WithApplyConcurrency(int) - limits the number of parallel threads. Default: ApplyDefaultConcurrency
//
// To stop processing, close `input` channel.
func ApplyChan[T any](input <-chan T, fn func(in T), opts ...ApplyOption) {
ops := parseApplyOptions(opts)
wg := sync.WaitGroup{}
// init goroutines limiter
limiter := NewConcurrencyLimiter(ops.concurrency)
// run callback for each input item
for item := range input {
limiter.Acquire()
wg.Add(1)
go func(item T) {
defer func() {
limiter.Release()
wg.Done()
}()
fn(item)
}(item)
}
wg.Wait()
}
// ApplySlice does the same as ApplyChan, but works with slice instead of a channel.
func ApplySlice[T any](input []T, fn func(in T), opts ...ApplyOption) {
ops := parseApplyOptions(opts)
// init goroutines limiter
limiter := NewConcurrencyLimiter(ops.concurrency)
wg := sync.WaitGroup{}
for _, item := range input {
limiter.Acquire()
wg.Add(1)
go func(item T) {
defer func() {
limiter.Release()
wg.Done()
}()
fn(item)
}(item)
}
wg.Wait()
}