forked from alitto/pond
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resultsubpool.go
92 lines (71 loc) · 1.78 KB
/
resultsubpool.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
84
85
86
87
88
89
90
91
92
package pond
import (
"context"
"errors"
"fmt"
"sync"
"github.com/alitto/pond/v2/internal/dispatcher"
)
type resultSubpool[R any] struct {
*resultPool[R]
parent *pool
waitGroup sync.WaitGroup
sem chan struct{}
}
func newResultSubpool[R any](maxConcurrency int, ctx context.Context, parent *pool) ResultPool[R] {
if maxConcurrency == 0 {
maxConcurrency = parent.MaxConcurrency()
}
if maxConcurrency < 0 {
panic(errors.New("maxConcurrency must be greater or equal to 0"))
}
if maxConcurrency > parent.MaxConcurrency() {
panic(fmt.Errorf("maxConcurrency cannot be greater than the parent pool's maxConcurrency (%d)", parent.MaxConcurrency()))
}
tasksLen := maxConcurrency
if tasksLen > MAX_TASKS_CHAN_LENGTH {
tasksLen = MAX_TASKS_CHAN_LENGTH
}
subpool := &resultSubpool[R]{
resultPool: &resultPool[R]{
pool: &pool{
ctx: ctx,
maxConcurrency: maxConcurrency,
},
},
parent: parent,
sem: make(chan struct{}, maxConcurrency),
}
subpool.pool.dispatcher = dispatcher.NewDispatcher(ctx, subpool.dispatch, tasksLen)
return subpool
}
func (p *resultSubpool[R]) dispatch(incomingTasks []any) {
p.waitGroup.Add(len(incomingTasks))
// Submit tasks
for _, task := range incomingTasks {
select {
case <-p.Context().Done():
// Context canceled, exit
return
case p.sem <- struct{}{}:
// Acquired the semaphore, submit another task
}
subpoolTask := subpoolTask[any]{
task: task,
sem: p.sem,
waitGroup: &p.waitGroup,
updateMetrics: p.updateMetrics,
}
p.parent.Go(subpoolTask.Run)
}
}
func (p *resultSubpool[R]) Stop() Task {
return Submit(func() {
p.dispatcher.CloseAndWait()
p.waitGroup.Wait()
close(p.sem)
})
}
func (p *resultSubpool[R]) StopAndWait() {
p.Stop().Wait()
}