doujiu3768 2013-08-30 01:18
浏览 62
已采纳

可以安全地重用sync.WaitGroup吗?

Can sync.WaitGroup be reused after Wait() is called?

func worker(who string, in <-chan int, wg *sync.WaitGroup) {
    for i := range in {
        fmt.Println(who, i)
        wg.Done()
    }
}

func main() {
    var wg sync.WaitGroup

    AIn := make(chan int, 1)
    BIn := make(chan int, 1)

    go worker("a:", AIn, &wg)
    go worker("b:", BIn, &wg)

    for i := 0; i < 4; i++ {
        wg.Add(2)
        AIn <- i
        BIn <- i
        wg.Wait()
        fmt.Println("main:", i)
    }
}

This play.golang.org/p/QLsvA-b4Ae runs as expected, but is it guaranteed to be safe? The documentation doesn't say so, but maybe I'm just being paranoid.

  • 写回答

1条回答 默认 最新

  • drby30217 2013-08-30 02:34
    关注

    Yes, it is safe. In fact, it is even safer than that. You can Wait from multiple goroutines concurrently, and interchange Add and Done calls as appropriate for your use case. As long as the Add happens before the Wait, you should be safe.

    Just out of curiosity, right now the WaitGroup is implemented with a mutex, two int32s counters, and a semaphore:

    type WaitGroup struct {
            m       Mutex
            counter int32
            waiters int32
            sema    *uint32
    }
    

    This is also an interesting test:

    var wg1, wg2 sync.WaitGroup
    wg1.Add(1)
    wg1.Done()
    wg1.Wait()
    fmt.Println(wg1 == wg2) // Prints true
    

    Finally, if you do find any issues with that kind of use, please report as it would be a bug.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀