简体   繁体   English

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()
}

If I remove wg and go, I receive the size of each url body correctly. 如果删除wg并走,我将正确接收每个URL主体的大小。 If I do it as in above, it prints zeroes almost instantly. 如果我按照上面的方法进行操作,它将几乎立即输出零。 The getUrlBody() takes time to execute sometimes minutes. getUrlBody()有时需要花费几分钟才能执行。

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... 我发现错误发生在getUrlBody和main()函数中...

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. 所有goroutine都共享一个myurl变量。 See https://golang.org/doc/faq#closures_and_goroutines for more information. 有关更多信息,请参见https://golang.org/doc/faq#closures_and_goroutines

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()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM