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..") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice and simple. Thank you
Go playground link: https://goplay.tools/snippet/VQI-w53V9TW