douju1968 2013-06-14 02:56
浏览 23
已采纳

Goroutine和频道通讯的奇怪行为

package main

import "fmt"

func main() {
  completed := make(chan bool, 2)
  m := map[string]string{"a": "a", "b": "b"}
  for k, v := range m {
    go func() {
      fmt.Println(k, v)
      completed <- true
    }()
  }
  <- completed
  <- completed
}

I ran the code hundreds of times, the output is always:

b b
b b

However, I have never seen pair a a printed. Is this some sort of weird concurrency issue?

  • 写回答

3条回答 默认 最新

  • dqk77945 2013-06-14 04:39
    关注

    This is a classic example of a "Race on counter loop". If you run your code with go run -race I suspect it will tell you that.

    The following will do what you expect:

    func main() {
      completed := make(chan bool, 2)
      m := map[string]string{"a": "a", "b": "b"}
      for k, v := range m {
        go func(k, v string) {
          fmt.Println(k, v)
          completed <- true
        }(k, v)
      }
      <- completed
      <- completed
    }
    

    Your original code is likely to print only b's (or only a's), on any machine, and in fact it happens on the Go playground: http://play.golang.org/p/Orgn030Yfr

    This is because the anonymous function is referring to the variables from the for k, v line, not the values that those variables happen to have at the moment the goroutine is created. First both variables are set to one value, and one goroutine is spawned, then they're set to the other value, and another goroutine is spawned. Then, both goroutines run, and they both see the newest values of k and v. By the way, this isn't really specific to multithreading or to Go (play.golang.org runs everything in a single thread and still shows this "bug.") This same problem happens in JavaScript where there is guaranteed to be only one thread:

    obj = {a: 'a', b: 'b'};
    for (k in obj) {
      setTimeout(function() { console.log(k, obj[k]); }, 0);
    }
    

    http://goo.gl/vwrMQ -- by the time the anonymous function runs, the for loop has finished, so 'k' is left with its most recent value for both runs of the function.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应