英文:
Spawning go routines in a loop with closure
问题
我有一个字符串列表,其中的元素数量可以从1到100,000不等。我想要验证每个字符串是否存储在数据库中,这需要进行网络调用。
为了最大化效率,我想为每个元素生成一个go routine。
目标是,如果go routine函数中的任何一个验证返回了err,则返回false,如果没有err,则返回true。因此,如果我们找到至少一个err,我们可以停止,因为我们已经知道它将返回false。
这是基本思路,下面的函数是我目前考虑使用的结构。我想知道是否有更好的方法(也许使用通道?)。
for _, id := range userIdList {
go func(id string){
user, err := verifyId(id)
if err != nil {
return err
}
// ...
// few more calls to other APIs for verifications
if err != nil {
return err
}
}(id)
}
英文:
I have a list of strings which can contain number of elements ranging from 1 to 100,000. I want to verify each string and see if they are stored in a database, which requires call to network.
In order to maximize the efficiency, I want to spawn a go routine for each element.
Goal is to return false if one of the verifications inside the go routine function returns err, and return true if there is no err. So if we find at least one err we can stop since we already know that it is going to return false.
This is the basic idea, and the function below is the structure I've been thinking about using so far. I'd like to know if there is a better way (perhaps using channel?).
for _, id := range userIdList {
go func(id string){
user, err := verifyId(id)
if err != nil {
return err
}
// ...
// few more calls to other APIs for verifications
if err != nil {
return err
}
}(id)
}
答案1
得分: 0
我写了一个可能对你有帮助的小函数。请查看有限并行操作。
英文:
I have wrote a small function that might be helpful for you.
Please take a look at limited parallel operations
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论