Skip to content

Instantly share code, notes, and snippets.

@xiongjia
Created April 24, 2025 17:07
Show Gist options
  • Save xiongjia/8fca648bc425ed69f5c71c9261e59167 to your computer and use it in GitHub Desktop.
Save xiongjia/8fca648bc425ed69f5c71c9261e59167 to your computer and use it in GitHub Desktop.
Wait Group
package util
import "sync"
type (
WaitGroup struct {
wg sync.WaitGroup
}
)
func NewWaitGroup() *WaitGroup {
return &WaitGroup{}
}
func (h *WaitGroup) Go(f func()) {
h.wg.Add(1)
go func() {
defer h.wg.Done()
f()
}()
}
func (h *WaitGroup) Wait() {
h.wg.Wait()
}
package util
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"go.uber.org/goleak"
)
func TestWg(t *testing.T) {
defer goleak.VerifyNone(t)
wg := util.NewWaitGroup()
var testData int
testData = 1
wg.Go(func() {
t.Log("Test1 is running")
time.Sleep(2 * time.Second)
testData = 2
t.Log("Test2 finished")
})
var testData2 int
testData2 = 1
wg.Go(func() {
t.Log("Test2 is running")
time.Sleep(1 * time.Second)
testData2 = 2
t.Log("Test1 finished")
})
wg.Wait()
t.Log("All tests finished")
assert.Equal(t, testData, 2)
assert.Equal(t, testData2, 2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment