英文:
Go Concurrency Pattern- will this leave hanging goroutines?
问题
在Rob Pike的Google IO演讲中,他提到了Go并发模式,并展示了这段代码作为从多个复制服务器中选择最快响应者的示例:
func First(query string, replicas ...Search) Result {
c := make(chan Result)
searchReplica := func(i int) { c <- replicas[i](query) }
for i := range replicas {
go searchReplica(i)
}
return <-c
}
问题:这样做会不会导致N-1个复制协程在通道写入时被阻塞?
在演讲后的讨论中,似乎有一个观众提出了这个问题,但得到了一个模糊的回答。
我倾向于将第三行改为以下内容:
searchReplica := func(i int) {
select {
case c <- replicas[i](query):
default: // 非阻塞写入
}
}
英文:
In Rob Pike's Google IO talk on Go Concurrency Patterns, he presented this code as an example of how to pick the fastest responder from a number of replica servers:
func First(query string, replicas ...Search) Result {
c := make(chan Result)
searchReplica := func(i int) { c <- replicas[i](query) }
for i := range replicas {
go searchReplica(i)
}
return <-c
}
Question: Won't this leave N-1 of the replica goroutines blocking on a channel write?
In the discussion after the talk, one of the audience members seems to be asking this question, but got kind of a handy-wavy response.
I'd be inclined to change the 3rd line to something like this:
searchReplica := func(i int) {
select {
case c <- replicas[i](query):
default: // non-blocking write
}
}
答案1
得分: 1
你是正确的。但这不适合放在一张幻灯片上。他谈论的是并发模式,而不是必须要用代码实现。
当然,我仍然不会把那段代码放在幻灯片上...
英文:
You are correct. But that doesn't fit on a single slide. He was talking about concurrency patterns, not necessarily the code to do it.
Of course, I still wouldn't have put that code on a slide...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论