Skip to content

Introduce ConcurrentAtomic and fix data race condition issue in Cocoa… #635

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

jeffery812
Copy link
Contributor

#630

ThreadSanitizer reported a data race issue when accessing the CocoaMQTTWebSocket.delegate and CocoaMQTTLogger.minLevel properties. The existing implementation assigns these properties asynchronously using a serial queue:

internal var internalQueue = DispatchQueue(label: "CocoaMQTTWebSocket")

public func setDelegate(_ theDelegate: CocoaMQTTSocketDelegate?, delegateQueue: DispatchQueue?) {
    internalQueue.async {
        self.delegate = theDelegate
        self.delegateQueue = delegateQueue
    }
}

Although a serial queue is used, the asynchronous call (async) does not guarantee timing consistency, which could lead to concurrent reads and writes if other parts of the code access delegate outside this queue.

Solution

Introduce ConcurrentAtomic object wrapper and annotate CocoaMQTTWebSocket.delegate and CocoaMQTTLogger.minLevel, make them thread safe. This ensures:
Multiple concurrent reads are allowed.
Writes are serialized with a barrier and will not happen concurrently with reads or other writes.

This approach ensures thread-safe reads and writes without blocking non-mutating operations.

@jeffery812 jeffery812 force-pushed the bugfix/fix-data-race-condition-issue branch from e73d4c6 to 591ea8d Compare April 28, 2025 07:54
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.

2 participants