forked from alitto/pond
-
Notifications
You must be signed in to change notification settings - Fork 0
/
result.go
67 lines (48 loc) · 1.75 KB
/
result.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
package pond
import (
"context"
"github.com/alitto/pond/v2/internal/future"
)
// ResultPool is a pool that can be used to submit tasks that return a result.
type ResultPool[R any] interface {
basePool
// Submits a task to the pool and returns a future that can be used to wait for the task to complete and get the result.
Submit(task func() R) Result[R]
// Submits a task to the pool and returns a future that can be used to wait for the task to complete and get the result.
SubmitErr(task func() (R, error)) Result[R]
// Creates a new subpool with the specified maximum concurrency.
NewSubpool(maxConcurrency int) ResultPool[R]
// Creates a new task group.
NewGroup() ResultTaskGroup[R]
// Creates a new task group with the specified context.
NewGroupContext(ctx context.Context) ResultTaskGroup[R]
}
type resultPool[R any] struct {
*pool
}
func (p *resultPool[R]) NewGroup() ResultTaskGroup[R] {
return newResultTaskGroup[R](p.pool, p.Context())
}
func (p *resultPool[R]) NewGroupContext(ctx context.Context) ResultTaskGroup[R] {
return newResultTaskGroup[R](p.pool, ctx)
}
func (p *resultPool[R]) Submit(task func() R) Result[R] {
return p.submit(task)
}
func (p *resultPool[R]) SubmitErr(task func() (R, error)) Result[R] {
return p.submit(task)
}
func (p *resultPool[R]) submit(task any) Result[R] {
future, resolve := future.NewValueFuture[R](p.Context())
wrapped := wrapTask[R, func(R, error)](task, resolve)
p.dispatcher.Write(wrapped)
return future
}
func (p *resultPool[R]) NewSubpool(maxConcurrency int) ResultPool[R] {
return newResultSubpool[R](maxConcurrency, p.Context(), p.pool)
}
func NewResultPool[R any](maxConcurrency int, options ...Option) ResultPool[R] {
return &resultPool[R]{
pool: newPool(maxConcurrency, options...),
}
}