sync.WaitGroup不等待 [英] sync.WaitGroup doesnt waits
问题描述
可能是我看不到明显的东西,我在做什么错了:
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()
}
如果我删除wg并走了,我会收到每个网址正文的大小正确地。如果我像上面那样做,它几乎立即打印零。 getUrlBody()有时要花几分钟才能执行。
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.
答案:我也尝试过这种方法,可以肯定的是,它也表现出相同的行为。
我发现错误在于getUrlBody和main()函数...
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()
}
推荐答案
所有goroutine都共享单个 myurl
变量。有关更多信息,请参见 https://golang.org/doc/faq#closures_and_goroutines 。
All of the goroutines are sharing the single myurl
variable. See https://golang.org/doc/faq#closures_and_goroutines for more information.
将代码更改为:
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()
}
或
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()
}
这篇关于sync.WaitGroup不等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!