Timeout for WaitGroup.Wait()

前端 未结 7 808
清歌不尽
清歌不尽 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:01

    I did it like this: http://play.golang.org/p/eWv0fRlLEC

    go func() {
        wg.Wait()
        c <- struct{}{}
    }()
    timeout := time.Duration(1) * time.Second
    fmt.Printf("Wait for waitgroup (up to %s)\n", timeout)
    select {
    case <-c:
        fmt.Printf("Wait group finished\n")
    case <-time.After(timeout):
        fmt.Printf("Timed out waiting for wait group\n")
    }
    fmt.Printf("Free at last\n")
    

    It works fine, but is it the best way to do it?

提交回复
热议问题