dourong4031 2017-07-24 17:22
浏览 152
已采纳

带有i ++不一致添加的Golang for循环

I have for loop with goroutines. I create the go routines in the loop which prints a string and "i" which is an int. I know the strings and "i" will print in random order which it does. But "i" is not adding correctly as you can see below. The value stays the same for three or four of the five strings then jumps to 2 or 1. Shouldn't there be a 1, 2, 3, 4, 5 in the random order? What am I doing wrong?

package main

import (
    "fmt"
    "sync"
)

func main() {
    a := []string{
        "apple",
        "orange",
        "grape",
        "peach",
        "lemon",
    }

    wg := sync.WaitGroup{}
    wg.Add(len(a))
    i := 0
    for _, v := range a {
        go func(a string) {
            fmt.Println(a, i)
            i++
            wg.Done()
        }(v)
    }
    wg.Wait()
}

Result 1:

orange 0
apple 0
lemon 0
peach 2
grape 0

Result 2:

lemon 0
grape 0
peach 0
apple 0
orange 1

My Goal (random order)

lemon 2
grape 4
peach 1
apple 0
orange 3
  • 写回答

2条回答 默认 最新

  • duanjizi9443 2017-07-24 17:26
    关注

    Through the closures all the goroutines share the same variable i. Try that instead:

    package main
    
    import (
        "fmt"
        "sync"
    )
    
    func main() {
        a := []string{
            "apple",
            "orange",
            "grape",
            "peach",
            "lemon",
        }
    
        wg := sync.WaitGroup{}
        wg.Add(len(a))
        for i, v := range a {
            go func(a string, j int) {
                fmt.Println(a, j)
                wg.Done()
            }(v,j)
        }
        wg.Wait()
    }
    

    Generally: In the program you posted you are reading i and writing i from different goroutines without any synchronisation. That is a data race. Anything could happen in that scenario.

    The go race detector even yells at you

    go run -race test.go
    apple 0
    ==================
    WARNING: DATA RACE
    Read at 0x00c420010268 by goroutine 7:
      main.main.func1()
          /home/erwo/test.go:22 +0x6d
    
    Previous write at 0x00c420010268 by goroutine 6:
      main.main.func1()
          /home/erwo/test.go:23 +0x191
    
    Goroutine 7 (running) created at:
      main.main()
          /home/erwo/test.go:25 +0x15f
    
    Goroutine 6 (finished) created at:
      main.main()
          /home/erwo/test.go:25 +0x15f
    ==================
    orange 1
    ==================
    WARNING: DATA RACE
    Read at 0x00c420010268 by goroutine 8:
      main.main.func1()
          /home/erwo/test.go:22 +0x6d
    
    Previous write at 0x00c420010268 by goroutine 6:
      main.main.func1()
          /home/erwo/test.go:23 +0x191
    
    Goroutine 8 (running) created at:
      main.main()
          /home/erwo/test.go:25 +0x15f
    
    Goroutine 6 (finished) created at:
      main.main()
          /home/erwo/test.go:25 +0x15f
    ==================
    peach 2
    grape 2
    lemon 4
    Found 2 data race(s)
    exit status 66
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!