Skip to content

Instantly share code, notes, and snippets.

@shravanasati
Last active August 9, 2021 06:08
Show Gist options
  • Save shravanasati/2a26b1f69ffc0e090bc87d180d224de5 to your computer and use it in GitHub Desktop.
Save shravanasati/2a26b1f69ffc0e090bc87d180d224de5 to your computer and use it in GitHub Desktop.
Two implementations of syncing all goroutines in go -> using waitgroups and channels.
This gist shows two examples of how to make all goroutines finish in a Go program. There are two implementations mentioned here:
1. Using channels
2. Using goroutines
// using channels to sync all goroutines
package main
import "fmt"
import "time"
func main() {
list := []string{
"1",
"2",
"3",
"4",
"5",
}
ch := make(chan string, len(list))
for _, v := range list {
go func(v string) {
time.Sleep(time.Second)
ch <- v
}(v)
}
// waiting for all goroutines to finish
for i := 0; i < len(list); i ++ {
fmt.Println(<- ch)
}
}
// using waitgroups to sync all goroutines
package main
import "fmt"
import "time"
import "sync"
func main() {
list := []string{
"1",
"2",
"3",
"4",
"5",
}
wg := sync.WaitGroup{}
wg.Add(len(list))
for _, v := range list {
go func(v string) {
time.Sleep(time.Second)
fmt.Println(v)
wg.Done()
}(v)
}
// waiting for all goroutines to finish
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment