Skip to content

Fix race condition during high CPU load in WebSocket::stop - #609

Open
cosminpolifronie wants to merge 1 commit into
machinezone:masterfrom
cosminpolifronie:fix-websocket-stop-race-condition
Open

cosminpolifronie wants to merge 1 commit into
machinezone:masterfrom
cosminpolifronie:fix-websocket-stop-race-condition

Conversation

@cosminpolifronie

Copy link
Copy Markdown
Contributor

We have found the bug below when using the library in production during high CPU load.
The fix has been tested and successfully eliminates the indefinite hang.

Could this please be merged and released? Thanks a lot!

Bug: if _stop is set only after close(), there is a window where close() has already driven the connection to CLOSED (e.g. a fast close round-trip, or the 300ms forced-close fallback) while _stop is still false. checkConnection()'s loop only bails out on isConnected() / isClosing() / _stop; if none of those are true yet and _automaticReconnection is enabled (the default), it will immediately reconnect - opening a brand new OPEN session that this call never asked to close. The run() thread then goes back into a blocking poll() on that new session, and _stop=true (set afterwards) is never observed by it in time: notify_one() only wakes the reconnection back-off wait, not the blocking poll() (which is only woken by the socket's own SelectInterrupt, and nothing triggers that again after this stop() call already used its one close()/wakeUpFromPoll). The result is that the join() below blocks forever.

Setting _stop = true first closes this race unconditionally: checkConnection()'s very first condition (isConnected() || isClosing() || _stop) will now always observe _stop == true before it could ever call connect() again, regardless of how the two threads interleave. The graceful close handshake performed by close() below is unaffected by this reordering (_stop is a WebSocket-level flag; the close/poll/dispatch machinery only look at the WebSocketTransport's own state).

…could trigger an automatic reconnect => _thread.join() blocks indefinitely
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant