在循环中使用闭包生成Go协程

huangapple go评论85阅读模式
英文:

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

huangapple
  • 本文由 发表于 2017年7月22日 02:24:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/45244386.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定