doutang3077 2018-03-11 19:26
浏览 41

索引超出范围goroutine golang

Index out of range error where it seems impossible in goroutine generated by for loop

This is the go code I am executing. The problem is that an index out of range error is yielded inside the evaluation of one of the arguments to countlinks call in a goroutine. The length of the slice we're iterating against is ALWAYS 2. Based on my understanding of for loops in go, i should never evaluate to 2 (yielding index out of range in expression grph.entryPoints[i]), and yet it is. Please, tell me how I am crazy.

func main() {
    grph := structures.ConfigGraphDefault()
    counter := structures.NewCounter()
    queue := structures.NewQueue()
    tracker := structures.NewTracker()
    fmt.Printf("entries: %v
nodes: %v
", grph.EntryPoints, grph.Nodes)
    wg := sync.WaitGroup{}
    fmt.Println(len(grph.EntryPoints))
    // this will always evaluate to 2
    l := len(grph.EntryPoints)
    for i := 0; i < l; i++ {
        wg.Add(1)
        go func() {
            fmt.Printf("index: %v, length of slice: %v
", i, len(grph.EntryPoints))
            structures.CountLinks(&grph, counter, queue, tracker, grph.EntryPoints[i], i)
            wg.Done()
        }()
    }
    wg.Wait()
    fmt.Printf("counter: %v", counter.GetCounts())
}
  • 写回答

1条回答 默认 最新

  • drtwqc3744 2018-03-11 19:32
    关注

    i does become 2, but only at the very end of the loop. But because your goroutine function closes over i, it doesn't see the value of i at the time the goroutine was started, but the value of i at the time it executes. In other words, all your goroutines share the same variable i.

    To fix this, one way is to copy i to a helper variable declared inside the loop body. A nicer way is to pass it as an argument to the goroutine:

        go func(i int) {
            fmt.Printf("index: %v, length of slice: %v
    ", i, len(grph.EntryPoints))
            structures.CountLinks(&grph, counter, queue, tracker, grph.EntryPoints[i], i)
            wg.Done()
        }(i)
    
    评论

报告相同问题?

悬赏问题

  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私