kone-net/go-chat

并发安全

ykaii opened this issue · 1 comments

ykaii commented

gorilla/websocket的文档写道:
Connections support one concurrent reader and one concurrent writer.

Applications are responsible for ensuring that no more than one goroutine calls the write methods (NextWriter, SetWriteDeadline, WriteMessage, WriteJSON, EnableWriteCompression, SetCompressionLevel) concurrently and that no more than one goroutine calls the read methods (NextReader, SetReadDeadline, ReadMessage, ReadJSON, SetPongHandler, SetPingHandler) concurrently.

The Close and WriteControl methods can be called concurrently with all other methods.

所以在读写websocket消息的两个goroutine中并发调用WriteMessage方法是不可以的

感谢提醒,在Client对象里面添加mu sync.Mutex互斥锁,调用Conn *websocket.Conn 写消息时,应该加锁和释放锁。