Timeout for WaitGroup.Wait()

前端 未结 7 827
清歌不尽
清歌不尽 2021-02-01 04:33

What is an idiomatic way to assign a timeout to WaitGroup.Wait() ?

The reason I want to do this, is to safeguard my \'scheduler\' from potentially awaiting an errant \'w

7条回答
  •  暖寄归人
    2021-02-01 05:08

    This is not an actual answer to this question but was the (much simpler) solution to my little problem when I had this question.

    My 'workers' were doing http.Get() requests so I just set the timeout on the http client.

    urls := []string{"http://1.jpg", "http://2.jpg"}
    wg := &sync.WaitGroup{}
    for _, url := range urls {
        wg.Add(1)
        go func(url string) {
            client := http.Client{
                Timeout: time.Duration(3 * time.Second), // only want very fast responses
            }
            resp, err := client.Get(url)
            //... check for errors
            //... do something with the image when there are no errors
            //...
    
            wg.Done()
        }(url)
    
    }
    wg.Wait()
    

提交回复
热议问题