Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix:add mutex in websocket ReadMessage() to prevent data race #3

Merged
merged 1 commit into from
Jun 3, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 17 additions & 5 deletions connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -489,8 +489,9 @@ func (u *gettyUDPConn) CloseConn(_ int) {

type gettyWSConn struct {
gettyConn
conn *websocket.Conn
lock sync.Mutex
writeLock sync.Mutex
readLock sync.Mutex
conn *websocket.Conn
}

// create websocket connection
Expand Down Expand Up @@ -565,7 +566,7 @@ func (w *gettyWSConn) handlePong(string) error {
func (w *gettyWSConn) recv() ([]byte, error) {
// Pls do not set read deadline when using ReadMessage. AlexStocks 20180310
// gorilla/websocket/conn.go:NextReader will always fail when got a timeout error.
_, b, e := w.conn.ReadMessage() // the first return value is message type.
_, b, e := w.threadSafeReadMessage() // the first return value is message type.
if e == nil {
w.readBytes.Add((uint32)(len(b)))
} else {
Expand Down Expand Up @@ -641,10 +642,21 @@ func (w *gettyWSConn) CloseConn(waitSec int) {

// uses a mutex to ensure that only one thread can send a message at a time, preventing race conditions.
func (w *gettyWSConn) threadSafeWriteMessage(messageType int, data []byte) error {
w.lock.Lock()
defer w.lock.Unlock()
w.writeLock.Lock()
defer w.writeLock.Unlock()
if err := w.conn.WriteMessage(messageType, data); err != nil {
return err
}
return nil
}

// uses a mutex to ensure that only one thread can read a message at a time, preventing race conditions.
func (w *gettyWSConn) threadSafeReadMessage() (int, []byte, error) {
w.readLock.Lock()
defer w.readLock.Unlock()
messageType, readBytes, err := w.conn.ReadMessage()
if err != nil {
return messageType, nil, err
}
return messageType, readBytes, nil
}
Loading