Timeout for WaitGroup.Wait()

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

    I wrote a library that encapsulates the concurrency logic https://github.com/shomali11/parallelizer which you can also pass a timeout.

    Here is an example without a timeout:

    func main() {
        group := parallelizer.DefaultGroup()
    
        group.Add(func() {
            for char := 'a'; char < 'a'+3; char++ {
                fmt.Printf("%c ", char)
            }
        })
    
        group.Add(func() {
            for number := 1; number < 4; number++ {
                fmt.Printf("%d ", number)
            }
        })
    
        err := group.Run()
    
        fmt.Println()
        fmt.Println("Done")
        fmt.Printf("Error: %v", err)
    }
    

    Output:

    a 1 b 2 c 3 
    Done
    Error: 
    

    Here is an example with a timeout:

    func main() {
        options := ¶llelizer.Options{Timeout: time.Second}
        group := parallelizer.NewGroup(options)
    
        group.Add(func() {
            time.Sleep(time.Minute)
    
            for char := 'a'; char < 'a'+3; char++ {
                fmt.Printf("%c ", char)
            }
        })
    
        group.Add(func() {
            time.Sleep(time.Minute)
    
            for number := 1; number < 4; number++ {
                fmt.Printf("%d ", number)
            }
        })
    
        err := group.Run()
    
        fmt.Println()
        fmt.Println("Done")
        fmt.Printf("Error: %v", err)
    }
    

    Output:

    Done
    Error: timeout
    

提交回复
热议问题