doumo0206 2017-12-30 19:34
浏览 80
已采纳

如何使用WaitGroup确保goroutine在for循环中完成?

I'm running a function in a goroutine each time a for-loop iterates, and I'm using sync.WaitGroup to make sure the goroutines all finish. However, I'm getting weird behavior testing the concurrency with counters. In the example below, I attempt to keep track of the thread count using 4 different techniques (w, x, y, z), and get 4 different results. The only result I understand is x, since it is incremented in the for-loop itself. What am I missing here?

package main

import "fmt"
import "sync"

var w = 0

func main() {
  x := 0
  y := 0
  z := 0
  var wg sync.WaitGroup
  for i := 0; i < 10000; i++ {
    wg.Add(1)
    x++
    go func() {
      z++
      test(&y)
      wg.Done()
    }()
  }
  wg.Wait()
  fmt.Println(w, x, y, z) // 8947 10000 8831 8816
}

func test(y *int) {
  w++
  *y++
}
  • 写回答

1条回答 默认 最新

  • duandang2838 2017-12-30 20:18
    关注

    The sync.Waitgroup is working as expected. w, y and z will not reach 10000 because multiple goroutines are incrementing them concurrently, and Go's increment is not concurrent-safe: it is implemented as a normal fetch-increment-reassign operation.

    You have two options.

    option 1: mutex

    type incrementer struct {
        sync.Mutex
        i int
    }
    
    func (i *incrementer) Add(n int) {
        i.Lock()
        defer i.Unlock()
        i.i += n
    }
    

    and use this type for w, y and z.

    Full example: https://play.golang.org/p/6wWUK2xnOCW

    option 2: sync.atomic

    var w int32 = 0
    
    go func(){
        // in the loop
        atomic.AddInt32(&w, 1)
    
    }()
    

    Full example: https://play.golang.org/p/oUCGgKYC1-Y

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

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助