dongqiang8683 2015-09-21 11:20
浏览 27
已采纳

使用Go中的select发送到频道有什么好处?

In the example directory of Gorilla websocket there is a file called hub.go.

https://github.com/gorilla/websocket/blob/master/examples/chat/hub.go

Here you can find a method on the type hub that does this.

func (h *hub) run() {
    for {
        select {
        case c := <-h.register:
            h.connections[c] = true
        case c := <-h.unregister:
            if _, ok := h.connections[c]; ok {
                delete(h.connections, c)
                close(c.send)
            }
        case m := <-h.broadcast:
            for c := range h.connections {
                select {
                case c.send <- m:
                default:
                    close(c.send)
                    delete(h.connections, c)
                }
            }
        }
    }
}

Why does it not just send to the c.send channel straight up in the last case like this?

case m := <-h.broadcast:
    for c := range h.connections {
        c.send <- m
    }
  • 写回答

2条回答 默认 最新

  • duanlachu7344 2015-09-21 11:31
    关注

    It's method of guaranted nonblocking send to channel. In case of c.send chan can't accept new messages now, a default branch will be executed. Without select{} block sending to unbuffered or fully filled buffered channel can be blocked.

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

报告相同问题?

悬赏问题

  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥15 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式