douyi1944 2018-07-18 06:27
浏览 58
已采纳

如何在没有隐式缓冲区的情况下将值从一个Go通道传输到另一个通道?

Imagine I have a goroutine that reads from one channel and writes to another.

ch1 := make(chan int)
ch2 := make(chan int)
go func() {
  for num := range ch1 {
    ch2 <- num+1
  }
}()

If ch2 is blocked, the goroutine will still read a value from ch1, effectively introducing a buffer of 1 in the channel. Since I'm using channels for control flow I don't want any buffering.

How can I make a pipeline that executes in a completely lock-step fashion? Or put differently, how can I transfer a value from one channel to the next in one atomic operation?

I basically want to wait for both ch1 and ch2 to be at a rendezvous point.

  • 写回答

1条回答 默认 最新

  • dongza3124 2018-07-18 06:44
    关注

    You can't do this with 2 channels. In order to perform a send on ch2, the value to be sent must already be ready, evaluated. Spec: Send statements:

    Both the channel and the value expression are evaluated before communication begins.

    So even if you would do this, which seemingly does not buffer the value in any variable:

    ch2 <- (<- ch1)
    

    Still, the receive from ch1 would be evaluated first, and only then would the send be attempted.

    Which means that value must have already been received from ch1. But you can't tell if anyone is "listening" on ch2 (meaning if a send on ch2 could proceed) without attempting to send on ch2 (and even if you could, there is no guarantee that attempting a send after a check there would still be someone listening on it).

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

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置