dongtou8736 2015-03-21 21:09
浏览 52
已采纳

Go并发模式-这会不会留下goroutines?

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条回答 默认 最新

  • drbii0359 2015-03-21 21:54
    关注

    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...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败