Skip to content

Instantly share code, notes, and snippets.

@jesselucas
Last active April 17, 2024 14:33
Show Gist options
  • Save jesselucas/179e70a684b6df18189fdaaa24f852cf to your computer and use it in GitHub Desktop.
Save jesselucas/179e70a684b6df18189fdaaa24f852cf to your computer and use it in GitHub Desktop.
Simple solution for using a WaitGroup with select{}
package main
import (
"fmt"
"sync"
"time"
)
func main() {
// Create a wait group of any size
wg := sync.WaitGroup{}
waitCh := make(chan struct{})
wg.Add(10)
// In another go routine Wait for the wait group to finish.
go func() {
// Run some actions
for i := 0; i < 10; i++ {
go func() {
defer wg.Done()
fmt.Println("do some action")
// Uncomment to show timeout.
// time.Sleep(100 * time.Millisecond)
}()
}
wg.Wait()
close(waitCh)
}()
// Block until the wait group is done or we timeout.
select {
case <-waitCh:
fmt.Println("WaitGroup finished!")
case <-time.After(100 * time.Millisecond):
fmt.Println("WaitGroup timed out..")
}
}
@IoIxD
Copy link

IoIxD commented Nov 15, 2022

On some versions of go (apparently?) you can't wait for a closed channel.
You should instead make a bool channel and do waitCh1 <- true
...apparently. Yeah this only cropped up in production its weird.

@shojaeix
Copy link

shojaeix commented Dec 8, 2022

Nice and simple. Thank you
Go playground link: https://goplay.tools/snippet/VQI-w53V9TW

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment