Go并发模式-这会导致悬挂的goroutine吗?

huangapple go评论65阅读模式
英文:

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 &lt;- replicas[i](query) }
    for i := range replicas {
        go searchReplica(i)
    }
    return &lt;-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 &lt;- 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...

huangapple
  • 本文由 发表于 2015年3月22日 05:09:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/29188072.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定