Last active
August 9, 2021 06:08
-
-
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 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
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 |
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
// 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) | |
} | |
} |
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
// 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