Skip to content

[question] concurrent write to websocket connection with mutex.Lock() #828

@Jrenk

Description

@Jrenk

Describe the problem you're having

Using the gorilla/websocket package I sometimes get the following error, despite using mutex.Lock:
concurrent write to websocket connection

Versions

  • Go version: 1.18
  • package version: v1.5.0

"Show me the code!"

type WebsocketClient struct {
	websocket   *websocket.Conn
	mutex            sync.Mutex
}

func (websocketClient *WebsocketClient) sendMessage(msg interface{}) error {
	websocketClient.mutex.Lock()
	defer websocketClient.mutex.Unlock()

	return websocketClient.websocket.WriteJSON(msg)
}

In an http handler the websocket clients get created:

ws, err := upgrader.Upgrade(w, r, nil)
...
clients[id] = &WebsocketClient{
    websocket: ws,
}

The sendMessage function gets called from multiple go-routines and the WriteJSON never gets called directly anywhere else. From my understanding the mutex.Lock() should prevent concurrent websocket writes.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions