douxi3554 2015-09-11 15:23
浏览 13
已采纳

我应该使用同步还是阻止频道?

I have several go routines and I use unbuffered channels as sync mechanism.

I'm wondering if there is anything wrong in this(e.g. compared with a WaitGroup implementation). A known "drawback" that I'm aware of is that two go routines may stay blocked until the 3rd(last) one completes because the channel is not buffered but I don't know the internals/what this really means.

func main() {
    chan1, chan2, chan3 := make(chan bool), make(chan bool), make(chan bool)
    go fn(chan1)
    go fn(chan2)
    go fn(chan3)
    res1, res2, res3 := <-chan1, <-chan2, <-chan3
}
  • 写回答

2条回答 默认 最新

  • doucuo9126 2015-09-11 20:06
    关注

    This implementation isn't inherently worse or better and I've written code of this style in favor of using a WaitGroup with success. I've also implemented the same functionality with WaitGroup and had roughly the same results. As mentioned in the comments which is better is situational, and likely subjective in many cases (the difference will be in maintainability or readability rather than performance).

    Personally, I really like this style for a situation where I'm spinning off one worker per item in a collection. I was already encountering a lot of pains with shutting down cleanly (signaling on an abort or close channel which had to be made available to the worker methods one way or another) so I thought it was very convenient to take that communication loop one step further and enclose all the work in a channel select. In order to have a working abort you kind of have to anyway.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件
  • ¥15 使用ESP8266连接阿里云出现问题