小编slo*_*dog的帖子

指数超出范围goroutine golang

索引超出范围错误,在for循环生成的goroutine中似乎不可能

这是我正在执行的代码.问题是索引超出范围错误是在对goroutine中countlinks调用的一个参数的评估中产生的.我们正在迭代的切片的长度总是2.基于我对go中的for循环的理解,i永远不应该评估为2(在表达式中产生索引超出范围grph.entryPoints[i]),但它是.拜托,告诉我我是多么疯狂.

func main() {
    grph := structures.ConfigGraphDefault()
    counter := structures.NewCounter()
    queue := structures.NewQueue()
    tracker := structures.NewTracker()
    fmt.Printf("entries: %v\nnodes: %v\n", 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\n", i, len(grph.EntryPoints))
            structures.CountLinks(&grph, counter, queue, tracker, grph.EntryPoints[i], i)
            wg.Done()
        }()
    }
    wg.Wait()
    fmt.Printf("counter: %v", counter.GetCounts())
}
Run Code Online (Sandbox Code Playgroud)

go goroutine

3
推荐指数
1
解决办法
517
查看次数

标签 统计

go ×1

goroutine ×1