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条)

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化