Skip to content

Commit 4b0db6b

Browse files
committed
feat: add builtin paralleler pool.
1 parent bdb10ca commit 4b0db6b

File tree

4 files changed

+29
-9
lines changed

4 files changed

+29
-9
lines changed

all.go

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -50,10 +50,14 @@ func AllWithContext(ctx context.Context, funcs ...AsyncFn) ([][]any, error) {
5050
// all executes the functions asynchronously until all functions have been finished, or the context
5151
// is done (canceled or timeout).
5252
func all(parent context.Context, funcs ...AsyncFn) ([][]any, error) {
53-
paralleler := new(Paralleler).
54-
WithContext(parent)
55-
56-
paralleler.Add(funcs...)
53+
paralleler := builtinPool.Get().(*Paralleler)
54+
defer func() {
55+
builtinPool.Put(paralleler)
56+
}()
57+
58+
paralleler.
59+
WithContext(parent).
60+
Add(funcs...)
5761

5862
return paralleler.Run()
5963
}

parallel.go

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,11 +48,15 @@ func ParallelWithContext(
4848

4949
// parallel runs the functions asynchronously with the specified concurrency.
5050
func parallel(parent context.Context, concurrency int, funcs ...AsyncFn) ([][]any, error) {
51-
paralleler := new(Paralleler).
52-
WithContext(parent).
53-
WithConcurrency(concurrency)
51+
paralleler := builtinPool.Get().(*Paralleler)
52+
defer func() {
53+
builtinPool.Put(paralleler)
54+
}()
5455

55-
paralleler.Add(funcs...)
56+
paralleler.
57+
WithContext(parent).
58+
WithConcurrency(concurrency).
59+
Add(funcs...)
5660

5761
return paralleler.Run()
5862
}

paralleler.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,13 @@ import (
55
"sync"
66
)
77

8+
// builtinPool is the Parallelers pool for built-in functions.
9+
var builtinPool sync.Pool = sync.Pool{
10+
New: func() any {
11+
return new(Paralleler)
12+
},
13+
}
14+
815
// Paralleler is a tool to run the tasks with the specific concurrency, default no concurrency
916
// limitation.
1017
type Paralleler struct {

times.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,12 @@ func TimesSeriesWithContext(ctx context.Context, n int, fn AsyncFn) ([][]any, er
5757

5858
// times executes the function n times withe the specified concurrency.
5959
func times(parent context.Context, n, concurrency int, fn AsyncFn) ([][]any, error) {
60-
paralleler := new(Paralleler).
60+
paralleler := builtinPool.Get().(*Paralleler)
61+
defer func() {
62+
builtinPool.Put(paralleler)
63+
}()
64+
65+
paralleler.
6166
WithConcurrency(concurrency).
6267
WithContext(parent)
6368

0 commit comments

Comments
 (0)