sync.WaitGroup和嵌套循环 [英] sync.WaitGroup and nested loops

查看:253
本文介绍了sync.WaitGroup和嵌套循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为并发嵌套循环添加并发性,但是遇到了麻烦.这个使用sync.WaitGroup的示例有什么问题?

I'd like to add concurrency for iterating nested loops but having a trouble. What's wrong with this example usage of sync.WaitGroup?

originCities := [3]string{"LED", "MOW", "PRS"}
destinationCities := [2]string{"UKT", "AAC"}

wg := &sync.WaitGroup{}
wg.Add(len(originCities) * len(destinationCities))

for _, originIata := range originCities {
    for _, destinationIata := range destinationCities {
        go func () {
            fmt.Println(originIata)
            fmt.Println(destinationIata)
            wg.Done()
        }()
    }
}
wg.Wait()

我要

PRS AAC PRS AAC PRS AAC PRS AAC PRS AAC PRS AAC

PRS AAC PRS AAC PRS AAC PRS AAC PRS AAC PRS AAC

因此,如您所见,它跳过了两个数组的第一个元素,仅对最后一个元素进行了迭代.任何想法如何解决此问题?

So as you may see it's skipping first elements of both array and iterating only the last ones. Any ideas how to fix this behavior?

推荐答案

这是一个关闭问题.您需要像这样在循环内将值传递给您的goroutine:

It's a closure problem. You need to pass values to your goroutine inside the loop, like this:

for _, originIata := range originCities {
    for _, destinationIata := range destinationCities {
        go func (originIata, destinationIata string) {
            fmt.Println(originIata)
            fmt.Println(destinationIata)
            wg.Done()
        }(originIata, destinationIata)
    }
}

这篇关于sync.WaitGroup和嵌套循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆