dqt83336 2013-08-02 07:42
浏览 22
已采纳

去引导两个以上的goroutines

One thing I do not like about Go is that channel receive also removes the data from the channel. This only allows two goroutines to communicate with each other even though there are several cases when two or more goroutines should be able to talk to each other.

I know I could make an array of channels and have channel per goroutine, but moving data from one goroutine to all of the other goroutines is much more data on ram than moving one copy of the data to all goroutines.

Think about a case when I have thousand clients connected to server and I want one to send message to only half of them that is five hundred goroutines receiving that message. If the message is 512 bytes this becomes 250 kilobytes of data in the ram moving, even though it's possible to move the same data only once if channels would not remove the data on receive.

So I am asking if there is some simple way to do this or do I have to use mutex from the sync package? Though please tell me if I am calculating wrong and channels do not copy the data, because in that case I can just manage array of channels.

  • 写回答

2条回答 默认 最新

  • dozrhldy285751 2013-08-02 08:02
    关注

    Read this article:

    http://rogpeppe.wordpress.com/2009/12/01/concurrent-idioms-1-broadcasting-values-in-go-with-linked-channels/

    It's an analysis on the different ways to channel-broadcast across goroutines, one of them being particularly interesting:

    type Broadcaster struct {
        Listenc chan chan (chan broadcast);
        Sendc   chan<- interface{};
    }
    

    This approach is called a "linked channel" (analagously to a linked list) by the author.

    tell me if I am calculating wrong and channels do not copy the data, because in that case I can just manage array of channels.

    You're not wrong. As @Jsor suggested, though - you can just pass pointers around if you're afraid of copy-overhead and the use case allows it.

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

报告相同问题?

悬赏问题

  • ¥20 安装 opencv4nodejs 报错
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!