【发布时间】:2022-11-02 10:04:55
【问题描述】:
我正在学习 Go 的并发模型,并从“Learning Go”一书中遇到了一个例子 - Oreilly。 在下面的示例中,“r := <-result”会阻塞,直到任何 Goroutine 写入结果通道,并且由于结果是无缓冲通道,后续从其他 Goroutine 写入结果将阻塞,直到结果通道再次为空。我的问题是,如果有 2 个 Goroutines 并行运行并同时写入结果通道(结果当时为空),在这种情况下,Go 运行时如何解决问题?
func searchData(s string, searchers []func(string) []string) []string {
done := make(chan struct{})
result := make(chan []string)
for i, searcher := range searchers {
go func(searcher func(string) []string) {
select {
case result <- searcher(s):
case <-done:
}
}(searcher)
}
r := <-result
close(done)
return r
}
【问题讨论】:
标签: go parallel-processing channel goroutine