我试图在 Go 中并行化递归问题,我不确定最好的方法是什么。
我有一个递归函数,它的工作原理如下:
func recFunc(input string) (result []string) {
for subInput := range getSubInputs(input) {
subOutput := recFunc(subInput)
result = result.append(result, subOutput...)
}
result = result.append(result, getOutput(input)...)
}
func main() {
output := recFunc("some_input")
...
}
因此,该函数调用自身时间(其中N在某个级别为0),生成自己的输出并返回列表中的所有内容。N
现在我想让这个函数并行运行。但我不确定最干净的方法来做到这一点。我的想法:
有一个“结果”通道,所有函数调用都向该通道发送其结果。
在 main 函数中收集结果。
有一个等待组,用于确定何时收集所有结果。
问题:我需要等待等待组并并行收集所有结果。我可以为此启动一个单独的 go 函数,但是我该如何退出这个单独的 go 函数呢?
func recFunc(input string) (result []string, outputChannel chan []string, waitGroup &sync.WaitGroup) {
defer waitGroup.Done()
waitGroup.Add(len(getSubInputs(input))
for subInput := range getSubInputs(input) {
go recFunc(subInput)
}
outputChannel <-getOutput(input)
}
func main() {
outputChannel := make(chan []string)
waitGroup := sync.WaitGroup{}
waitGroup.Add(1)
go recFunc("some_input", outputChannel, &waitGroup)
result := []string{}
go func() {
nextResult := <- outputChannel
result = append(result, nextResult ...)
}
waitGroup.Wait()
}
也许有更好的方法来做到这一点?或者,我如何确保收集结果的匿名 go 函数在完成时被截断?
小唯快跑啊
元芳怎么了
相关分类