May be I can not see obvious thing, what am I doing wrong:
func printSize (listOfUrls []string){
var wg sync.WaitGroup
wg.Add(len(listOfUrl))
for _, myurl := range(listOfUrls){
go func(){
body := getUrlBody(myurl)
fmt.Println(len(body))
wg.Done()
}()
}
wg.Wait()
}
If I remove wg and go, I receive the size of each url body correctly. If I do it as in above, it prints zeroes almost instantly. The getUrlBody() takes time to execute sometimes minutes.
Answering comment: I also tried it this way, to be sure, and it demonstrate same behaviour. I found the error was in getUrlBody and main() function...
func printSize(listOfUrls []string) {
var wg sync.WaitGroup
wg.Add(len(listOfUrls))
for _, myurl := range listOfUrls {
go f(myurl, &wg)
}
wg.Wait()
}
func f(myurl string, wg *sync.WaitGroup) {
body := getUrlBody(myurl)
fmt.Println(len(body))
wg.Done()
}
All of the goroutines are sharing the single myurl
variable. See https://golang.org/doc/faq#closures_and_goroutines for more information.
Change the code to:
func f(listOfUrls []string){
var wg sync.WaitGroup
wg.Add(len(listOfUrl))
for _, myurl := range(listOfUrls){
go func(myurl string){
body := getUrlBody(myurl)
fmt.Println(len(body))
wg.Done()
}(myurl)
}
wg.Wait()
}
or
func f(listOfUrls []string){
var wg sync.WaitGroup
wg.Add(len(listOfUrl))
for _, myurl := range(listOfUrls){
myurl := myurl
go func(){
body := getUrlBody(myurl)
fmt.Println(len(body))
wg.Done()
}()
}
wg.Wait()
}