What is the benefit of sending to a channel by using select in Go? -


in example directory of gorilla websocket there file called hub.go.

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

here can find method on type hub this.

func (h *hub) run() {     {         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:             c := range h.connections {                 select {                 case c.send <- m:                 default:                     close(c.send)                     delete(h.connections, c)                 }             }         }     } } 

why not send c.send channel straight in last case this?

case m := <-h.broadcast:     c := range h.connections {         c.send <- m     } 

it's method of guaranted nonblocking send channel. in case of c.send chan can't accept new messages now, default branch executed. without select{} block sending unbuffered or filled buffered channel can blocked.


Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -