From 187283c8844eb28224a8d617caecb0c7cbf5559e Mon Sep 17 00:00:00 2001 From: "Derrick J. Wippler" Date: Wed, 13 Feb 2019 14:20:02 -0600 Subject: [PATCH] Added WaitGroup.Go() --- version | 2 +- waitgroup.go | 16 +++++++++++++++- waitgroup_test.go | 23 ++++++++++++++++++++--- 3 files changed, 36 insertions(+), 5 deletions(-) diff --git a/version b/version index 0bee604d..3f684d2d 100644 --- a/version +++ b/version @@ -1 +1 @@ -2.3.3 +2.3.4 diff --git a/waitgroup.go b/waitgroup.go index ae18bbbf..eb4cf2d7 100644 --- a/waitgroup.go +++ b/waitgroup.go @@ -25,7 +25,6 @@ type WaitGroup struct { } // Run a routine and collect errors if any -//func (wg *WaitGroup) Run(callBack func() error) { func (wg *WaitGroup) Run(callBack func(interface{}) error, data interface{}) { wg.wg.Add(1) go func() { @@ -41,6 +40,21 @@ func (wg *WaitGroup) Run(callBack func(interface{}) error, data interface{}) { }() } +// Execute a long running routine +func (wg *WaitGroup) Go(cb func()) { + wg.wg.Add(1) + go func() { + err := cb + if err == nil { + wg.wg.Done() + return + } + wg.mutex.Lock() + wg.wg.Done() + wg.mutex.Unlock() + }() +} + // Run a goroutine in a loop continuously, if the callBack returns false the loop is broken. // `Until()` differs from `Loop()` in that if the `Stop()` is called on the WaitGroup // the `done` channel is closed. Implementations of the callBack function can listen diff --git a/waitgroup_test.go b/waitgroup_test.go index 0884d68f..671cc694 100644 --- a/waitgroup_test.go +++ b/waitgroup_test.go @@ -17,16 +17,16 @@ package holster_test import ( "sync/atomic" + "testing" "time" + "github.com/mailgun/holster" "github.com/pkg/errors" "github.com/stretchr/testify/suite" "gopkg.in/ahmetb/go-linq.v3" - "testing" - "github.com/mailgun/holster" ) -type WaitGroupTestSuite struct{ +type WaitGroupTestSuite struct { suite.Suite } @@ -59,6 +59,23 @@ func (s *WaitGroupTestSuite) TestRun() { s.Equal(true, linq.From(errs).Contains(items[1])) } +func (s *WaitGroupTestSuite) TestGo() { + var wg holster.WaitGroup + + wg.Go(func() { + // Do some long running thing + time.Sleep(time.Nanosecond * 500) + }) + + wg.Go(func() { + // Do some long running thing + time.Sleep(time.Nanosecond * 50) + }) + + errs := wg.Wait() + s.Nil(errs) +} + func (s *WaitGroupTestSuite) TestLoop() { pipe := make(chan int32, 0) var wg holster.WaitGroup