简体   繁体   English

如何使用通道确保多个 go 例程完成

[英]How to use a channel to make sure multiple go routines are done

I'm tying to execute things async with multiple go routines.我正在尝试使用多个 go 例程异步执行事物。 I pass in the number of "threads" to use to process.我传入了用于处理的“线程”数。

func refresh() {
    sign := make(chan int, len(allSets))
    for _, set := range allSets {
        i := int(set.GetId())
        if statement {
            // Update
            go UpdateKeywordSearcher(i, sign)
        }
    }

    // for this part, I wanna call some func after above all for..loop UpdateKeywordSearcher done
    // call anotherFunc()
} 
    
func UpdateKeywordSearcher(setid int, sign chan int) {
   // do some update logic
   sign <- setid
}

as above written codes, how can I call another method after all multiple go routine finished?如上编写的代码,在所有多个go例程完成后如何调用另一个方法? I searched for select but don't know what exactly I should write.我搜索了 select 但不知道我应该写什么。

As others have suggested, a sync.WaitGroup is probably the most sensible thing to use here.正如其他人所建议的那样, sync.WaitGroup可能是这里使用的最明智的选择。 That said, you can do what you want to achieve by reading the right number of items of the signal channel.也就是说,您可以通过读取信号通道的正确数量的项目来实现您想要实现的目标。

For example (I've simplified your example a bit but this should give you the idea):例如(我已经简化了你的例子,但这应该给你的想法):

package main

func main() {
    allSets := []int{1,2,3,4,5,6}
    sign := make(chan int)
    
    for _, id := range allSets {
        go UpdateKeywordSearcher(id, sign)
    }
    
    for i := 0; i < len(allSets); i++ {
        <-sign
    }
    
    close(sign) // Close the channel now we are done with it
    
    println("Done")
}
    
func UpdateKeywordSearcher(setid int, sign chan int) {
    // do some update logic
    sign <- setid
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM