Last active
April 17, 2024 14:33
-
-
Save jesselucas/179e70a684b6df18189fdaaa24f852cf to your computer and use it in GitHub Desktop.
Simple solution for using a WaitGroup with select{}
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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..") | |
} | |
} |
thanks
学长好哈哈哈,真巧在这遇到了你
😄thanks
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.
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
👍 thanks