V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
hijoker
V2EX  ›  Go 编程语言

golang 中的 sync.WaitGroup 这样用好么

  •  
  •   hijoker · 2020-07-20 15:13:11 +08:00 · 2037 次点击
    这是一个创建于 1369 天前的主题,其中的信息可能已经有所发展或是发生改变。
    把.Add()放到 goroutine 里面

    8 条回复    2020-07-21 09:52:14 +08:00
    keepeye
        1
    keepeye  
       2020-07-20 15:16:31 +08:00
    可以的
    janxin
        2
    janxin  
       2020-07-20 15:19:33 +08:00   ❤️ 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  
       2020-07-20 15:20:28 +08:00   ❤️ 1
    如果你是希望等待所有 goroutine 完成的话,那么 wg.Add(1)最好放到 go 函数外部, defer wg.Done() 放到函数内部
    Vegetable
        4
    Vegetable  
       2020-07-20 15:22:32 +08:00
    defer 没问题,但是 Add 最好放外边,虽然他在第一行,但是未必会比 wait 先执行。
    TypeErrorNone
        5
    TypeErrorNone  
       2020-07-20 15:55:30 +08:00
    不可以
    reus
        6
    reus  
       2020-07-20 19:11:56 +08:00
    这样用是错的,有可能没 Add,Wait 就执行了,起不到 Wait 的作用
    sxfscool
        7
    sxfscool  
       2020-07-21 08:36:56 +08:00
    我觉得不行, wait()可能直接过去,一个也等不到
    hijoker
        8
    hijoker  
    OP
       2020-07-21 09:52:14 +08:00
    这是 minikube 的源代码, 我看到的时候也是惊呆了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5220 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 07:19 · PVG 15:19 · LAX 00:19 · JFK 03:19
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.