-
Notifications
You must be signed in to change notification settings - Fork 191
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add sync errgroup to goutil package
- Loading branch information
Showing
3 changed files
with
49 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
package goutil | ||
|
||
import ( | ||
"context" | ||
|
||
"golang.org/x/sync/errgroup" | ||
) | ||
|
||
// ErrGroup is a collection of goroutines working on subtasks that | ||
// are part of the same overall task. | ||
// | ||
// Refers: | ||
// | ||
// https://github.com/neilotoole/errgroup | ||
// https://github.com/fatih/semgroup | ||
type ErrGroup struct { | ||
*errgroup.Group | ||
} | ||
|
||
// NewCtxErrGroup instance | ||
func NewCtxErrGroup(ctx context.Context, limit ...int) (*ErrGroup, context.Context) { | ||
egg, ctx1 := errgroup.WithContext(ctx) | ||
if len(limit) > 0 && limit[0] > 0 { | ||
egg.SetLimit(limit[0]) | ||
} | ||
|
||
eg := &ErrGroup{Group: egg} | ||
return eg, ctx1 | ||
} | ||
|
||
// NewErrGroup instance | ||
func NewErrGroup(limit ...int) *ErrGroup { | ||
eg := &ErrGroup{Group: new(errgroup.Group)} | ||
|
||
if len(limit) > 0 && limit[0] > 0 { | ||
eg.SetLimit(limit[0]) | ||
} | ||
return eg | ||
} | ||
|
||
// Add one or more handler at once | ||
func (g *ErrGroup) Add(handlers ...func() error) { | ||
for _, handler := range handlers { | ||
g.Go(handler) | ||
} | ||
} |