https://github.com/rfyiamcool/waitgroup
waitgroup that supports context and timeout.
https://github.com/rfyiamcool/waitgroup
waitgroup
Last synced: 8 months ago
JSON representation
waitgroup that supports context and timeout.
- Host: GitHub
- URL: https://github.com/rfyiamcool/waitgroup
- Owner: rfyiamcool
- Created: 2020-10-02T14:08:30.000Z (over 5 years ago)
- Default Branch: main
- Last Pushed: 2020-10-13T05:39:17.000Z (over 5 years ago)
- Last Synced: 2025-10-14T17:40:39.010Z (8 months ago)
- Topics: waitgroup
- Language: Go
- Homepage:
- Size: 4.88 KB
- Stars: 20
- Watchers: 3
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# waitgroup
`extend std waitgroup`
**feature:**
- easy api
- add timeout
- add context
- concurrency go func
`when waitgroup force to exit with timeout, may cause goroutines leak problem.`
## usage:
see more example in test
[example](waitgroup_test.go)
```go
func Test_Simple(t *testing.T) {
counter := 0
lock := sync.Mutex{}
fn := func() error {
lock.Lock()
defer lock.Unlock()
counter++
return nil
}
wg, ctx := New()
wg.Async(fn)
wg.AsyncMany(fn, 5)
<-ctx.Done()
wg.Wait()
assert.Equal(t, wg.IsError(), false)
assert.Equal(t, counter, 6)
}
func Test_Ctx(t *testing.T) {
counter := 0
lock := sync.Mutex{}
fn := func() error {
lock.Lock()
defer lock.Unlock()
counter++
return nil
}
errval := errors.New("errfn")
errfn := func() error {
lock.Lock()
defer lock.Unlock()
counter++
return errval
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
wg, cctx := NewWithContext(ctx)
wg.Async(errfn)
wg.AsyncMany(fn, 5)
select {
case <-cctx.Done():
case <-ctx.Done():
}
assert.Equal(t, counter, 6)
assert.Equal(t, wg.IsError(), true)
assert.Equal(t, errval, wg.Errs[0])
}
func Test_WaitTimeout(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
wg, cctx := NewWithContext(ctx)
// _ = cctx
wg.Async(
func() error {
time.Sleep(5 * time.Second)
return io.ErrClosedPipe
},
)
wg.WaitTimeout(1 * time.Second)
<-cctx.Done()
}
```