Example for sync.WaitGroup correct?

后端 未结 3 822
北荒
北荒 2020-11-28 19:10

Is this example usage of sync.WaitGroup correct? It gives the expected result, but I am unsure about the wg.Add(4) and the position of wg.Don

3条回答
  •  自闭症患者
    2020-11-28 19:59

    I would recommend embeding the wg.Add() call into the doSomething() function itself, so that if you adjust the number of times it's called, you don't have to separately adjust the add parameter manually which could lead to an error if you update one but forget to update the other (in this trivial example that is unlikely, but still, I personally believe it to be better practice for code re-use).

    As Stephen Weinberg points out in his answer to this question, you do have to increment the waitgroup prior to spawning the gofunc, but you can accomplish this easily by wrapping the gofunc spawn inside the doSomething() function itself, like this:

    func dosomething(millisecs time.Duration, wg *sync.WaitGroup) {
        wg.Add(1)
        go func() {
            duration := millisecs * time.Millisecond
            time.Sleep(duration)
            fmt.Println("Function in background, duration:", duration)
            wg.Done()
        }()
    }
    

    Then you can call it without the go invocation, e.g.:

    func main() {
        var wg sync.WaitGroup
        dosomething(200, &wg)
        dosomething(400, &wg)
        dosomething(150, &wg)
        dosomething(600, &wg)
        wg.Wait()
        fmt.Println("Done")
    }
    

    As a playground: http://play.golang.org/p/WZcprjpHa_

提交回复
热议问题