proper way of waiting for a go routine to finish

后端 未结 2 1478
无人及你
无人及你 2020-12-19 21:10

I wish to know what is the proper way of waiting for a go routine to finish before exiting the program. Reading some other answers it seems that a bool chan will do the tric

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-19 21:35

    Listening to channel <- done, is a blocking operation, so your program won't continue until true or false is sent i.e. done <- true.

    Your question can have a few different answers depending on the circumstance.

    For instance, suppose you wanted to parallelize a series of function calls that take a long time.

    I would use the sync package for this

    package main
    
    import (
        "fmt"
        "sync"
        "time"
    )
    
    func main() {
        var wg sync.WaitGroup
        for i := 0; i < 10; i++ {
            wg.Add(1)
            go func() {
                longOp()
                wg.Done()
            }()
        }
        // will wait until wg.Done is called 10 times
        // since we made wg.Add(1) call 10 times
        wg.Wait()
    }
    
    func longOp() {
        time.Sleep(time.Second * 2)
        fmt.Println("long op done")
    }
    

提交回复
热议问题