sync.WaitGroup doesnt waits

后端 未结 1 1437
北荒
北荒 2020-12-22 14:12

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         


        
相关标签:
1条回答
  • 2020-12-22 14:21

    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()
    }
    
    0 讨论(0)
提交回复
热议问题