在Golang中,WaitGroup主要用来做go Routine的等待,当启动多个go程序,通过waitgroup可以等待所有go程序结束后再执行后面的代码逻辑,比如:

  1. func Main() {
  2. wg := sync.WaitGroup{}
  3. for i := 0; i < 10; i++ {
  4. wg.Add(1)
  5. go func() {
  6. defer wg.Done()
  7. time.Sleep(10 * time.Second)
  8. }()
  9. }
  10. wg.Wait() // 等待在此,等所有go func里都执行了Done()才会退出
  11. }

WaitGroup主要是三个方法,Add(int),Done()和Wait(), 其中Done()是调用了Add(-1)。

WaitGroup主要维护了2个计数器,一个是请求计数器 v,一个是等待计数器 w,二者组成一个64bit的值,请求计数器占高32bit,等待计数器占低32bit。

简单来说,当Add(n)执行时,请求计数器 v 就会加n,当Done()执行时,v 就会减1,可以想到,v 为0时就是结束,可以触发Wait()执行了,所谓的触发Wait()是通过信号量实现的。

那么等待计数器拿来干嘛?是因为Wait()方法支持并发,每一次Wait()方法执行,等待计数器 w 就会加1,而等待v为0触发Wait()时,要根据w的数量发送w份的信号量,正确的触发所有的Wait()。

同时,WaitGroup里还有对使用逻辑进行了严格的检查,比如Wait()一旦开始不能Add().

下面是带注释的代码:

  1. func (wg *WaitGroup) Add(delta int) {
  2. statep := wg.state()
  3. // 更新statep,statep将在wait和add中通过原子操作一起使用
  4. state := atomic.AddUint64(statep, uint64(delta)<<32)
  5. v := int32(state >> 32)
  6. w := uint32(state)
  7. if v < 0 {
  8. panic("sync: negative WaitGroup counter")
  9. }
  10. if w != 0 && delta > 0 && v == int32(delta) {
  11. // wait不等于0说明已经执行了Wait,此时不容许Add
  12. panic("sync: WaitGroup misuse: Add called concurrently with Wait")
  13. }
  14. // 正常情况,Add会让v增加,Done会让v减少,如果没有全部Done掉,此处v总是会大于0的,直到v为0才往下走
  15. // 而w代表是有多少个goruntine在等待done的信号,wait中通过compareAndSwap对这个w进行加1
  16. if v > 0 || w == 0 {
  17. return
  18. }
  19. // This goroutine has set counter to 0 when waiters > 0.
  20. // Now there can't be concurrent mutations of state:
  21. // - Adds must not happen concurrently with Wait,
  22. // - Wait does not increment waiters if it sees counter == 0.
  23. // Still do a cheap sanity check to detect WaitGroup misuse.
  24. // 当v为0(Done掉了所有)或者w不为0(已经开始等待)才会到这里,但是在这个过程中又有一次Add,导致statep变化,panic
  25. if *statep != state {
  26. panic("sync: WaitGroup misuse: Add called concurrently with Wait")
  27. }
  28. // Reset waiters count to 0.
  29. // 将statep清0,在Wait中通过这个值来保护信号量发出后还对这个Waitgroup进行操作
  30. *statep = 0
  31. // 将信号量发出,触发wait结束
  32. for ; w != 0; w-- {
  33. runtime_Semrelease(&wg.sema, false)
  34. }
  35. }
  36. // Done decrements the WaitGroup counter by one.
  37. func (wg *WaitGroup) Done() {
  38. wg.Add(-1)
  39. }
  40. // Wait blocks until the WaitGroup counter is zero.
  41. func (wg *WaitGroup) Wait() {
  42. statep := wg.state()
  43. for {
  44. state := atomic.LoadUint64(statep)
  45. v := int32(state >> 32)
  46. w := uint32(state)
  47. if v == 0 {
  48. // Counter is 0, no need to wait.
  49. if race.Enabled {
  50. race.Enable()
  51. race.Acquire(unsafe.Pointer(wg))
  52. }
  53. return
  54. }
  55. // Increment waiters count.
  56. // 如果statep和state相等,则增加等待计数,同时进入if等待信号量
  57. // 此处做CAS,主要是防止多个goroutine里进行Wait()操作,每有一个goroutine进行了wait,等待计数就加1
  58. // 如果这里不相等,说明statep,在 从读出来 到 CAS比较 的这个时间区间内,被别的goroutine改写了,那么不进入if,回去再读一次,这样写避免用锁,更高效些
  59. if atomic.CompareAndSwapUint64(statep, state, state+1) {
  60. if race.Enabled && w == 0 {
  61. // Wait must be synchronized with the first Add.
  62. // Need to model this is as a write to race with the read in Add.
  63. // As a consequence, can do the write only for the first waiter,
  64. // otherwise concurrent Waits will race with each other.
  65. race.Write(unsafe.Pointer(&wg.sema))
  66. }
  67. // 等待信号量
  68. runtime_Semacquire(&wg.sema)
  69. // 信号量来了,代表所有Add都已经Done
  70. if *statep != 0 {
  71. // 走到这里,说明在所有Add都已经Done后,触发信号量后,又被执行了Add
  72. panic("sync: WaitGroup is reused before previous Wait has returned")
  73. }
  74. return
  75. }
  76. }
  77. }

 

版权声明:本文为jiangz222原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/jiangz222/p/10348763.html