Skip to content

Commit

Permalink
Merge pull request #53 from craigpastro/add-wait-safe-method
Browse files Browse the repository at this point in the history
Add WaitAndRecover method to WaitGroup
  • Loading branch information
camdencheek committed Jan 13, 2023
2 parents dbf8973 + 83a01d6 commit ec1413e
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
9 changes: 9 additions & 0 deletions waitgroup.go
Expand Up @@ -41,3 +41,12 @@ func (h *WaitGroup) Wait() {
// Propagate a panic if we caught one from a child goroutine.
h.pc.Repanic()
}

// WaitAndRecover will block until all goroutines spawned with Go exit and
// will return a *panics.RecoveredPanic if one of the child goroutines panics.
func (h *WaitGroup) WaitAndRecover() *panics.RecoveredPanic {
h.wg.Wait()

// Return a recovered panic if we caught one from a child goroutine.
return h.pc.Recovered()
}
41 changes: 41 additions & 0 deletions waitgroup_test.go
Expand Up @@ -98,5 +98,46 @@ func TestWaitGroup(t *testing.T) {
require.Panics(t, wg.Wait)
require.Equal(t, int64(2), i.Load())
})

t.Run("is caught by waitandrecover", func(t *testing.T) {
t.Parallel()
var wg WaitGroup
wg.Go(func() {
panic("super bad thing")
})
p := wg.WaitAndRecover()
require.Equal(t, p.Value, "super bad thing")
})

t.Run("one is caught by waitandrecover", func(t *testing.T) {
t.Parallel()
var wg WaitGroup
wg.Go(func() {
panic("super bad thing")
})
wg.Go(func() {
panic("super badder thing")
})
p := wg.WaitAndRecover()
require.NotNil(t, p)
})

t.Run("nonpanics run successfully with waitandrecover", func(t *testing.T) {
t.Parallel()
var wg WaitGroup
var i atomic.Int64
wg.Go(func() {
i.Add(1)
})
wg.Go(func() {
panic("super bad thing")
})
wg.Go(func() {
i.Add(1)
})
p := wg.WaitAndRecover()
require.Equal(t, p.Value, "super bad thing")
require.Equal(t, int64(2), i.Load())
})
})
}

0 comments on commit ec1413e

Please sign in to comment.