
让我们看一下扇入模式。当我们需要将来自多个线程的相关数据汇集在一起时,这在 go 中非常有用。
例如,假设您对不同的服务进行了多个 api 调用,并且需要合并结果。
这是一个非常容易实现的模式,但您确实需要注意如何处理通道。很容易出现死锁情况。
// produce is used to simulate the different data sources
func produce(id int) chan int {
ch := make(chan int)
go func() {
for i := 0; i < 10; i++ {
ch <- id*10 + i
}
fmt.Printf("producer %d done\n", id)
close(ch) // this is important!!!
}()
return ch
}
func fanin(inputs ...chan int) chan int {
output := make(chan int)
var wg sync.WaitGroup
for i, input := range inputs {
wg.Add(1)
go func() {
for value := range input {
output <- value
}
fmt.Printf("done merging source %d\n", i)
wg.Done()
}()
}
go func() {
wg.Wait()
close(output) // this is important!!!
}()
return output
}
func main() {
input1 := produce(0)
input2 := produce(1)
result := fanin(input1, input2)
done := make(chan bool)
go func() {
for value := range result {
fmt.Printf("got %d\n", value)
}
close(done)
}()
<-done
fmt.Println("done")
}
这里我们使用 produce 函数来模拟不同的来源。这些源通道被发送到执行组合操作的 fanin 函数。
fanin 函数创建输出通道,然后启动一个对每个输入进行操作的 goroutine。我们使用 waitgroup 来指示所有输入源何时组合到输出通道中。
在这个简单的示例中,主线程只是迭代输出。请注意,无法保证顺序,两个输入的值是混合的。
要提出的一个关键点是,当我们完成组合输入时,我们必须关闭输出通道。一旦通道为空,范围运算符将无限期等待。注释掉 close(output) 行,您将看到出现死锁情况。
我们如何改进这一点?请在下面给我留言吧。
谢谢!
这篇文章以及本系列所有文章的代码可以在这里找到
以上就是Go 中的 Fanin 模式的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号