V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
hijoker

golang 中的 sync.WaitGroup 这样用好么

  •  
  •   hijoker · Jul 20, 2020 · 2745 views
    This topic created in 2116 days ago, the information mentioned may be changed or developed.
    把.Add()放到 goroutine 里面

    8 replies    2020-07-21 09:52:14 +08:00
    keepeye
        1
    keepeye  
       Jul 20, 2020
    可以的
    janxin
        2
    janxin  
       Jul 20, 2020   ❤️ 1
    官方文档这里说的很清楚

    Note that calls with a positive delta that occur when the counter is zero must happen before a Wait. Calls with a negative delta, or calls with a positive delta that start when the counter is greater than zero, may happen at any time. Typically this means the calls to Add should execute before the statement creating the goroutine or other event to be waited for. If a WaitGroup is reused to wait for several independent sets of events, new Add calls must happen after all previous Wait calls have returned. See the WaitGroup example.
    sunxiansong
        3
    sunxiansong  
       Jul 20, 2020   ❤️ 1
    如果你是希望等待所有 goroutine 完成的话,那么 wg.Add(1)最好放到 go 函数外部, defer wg.Done() 放到函数内部
    Vegetable
        4
    Vegetable  
       Jul 20, 2020
    defer 没问题,但是 Add 最好放外边,虽然他在第一行,但是未必会比 wait 先执行。
    TypeErrorNone
        5
    TypeErrorNone  
       Jul 20, 2020
    不可以
    reus
        6
    reus  
       Jul 20, 2020
    这样用是错的,有可能没 Add,Wait 就执行了,起不到 Wait 的作用
    sxfscool
        7
    sxfscool  
       Jul 21, 2020
    我觉得不行, wait()可能直接过去,一个也等不到
    hijoker
        8
    hijoker  
    OP
       Jul 21, 2020
    这是 minikube 的源代码, 我看到的时候也是惊呆了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3290 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 257ms · UTC 12:33 · PVG 20:33 · LAX 05:33 · JFK 08:33
    ♥ Do have faith in what you're doing.