fix(Foundation): Fix deadlock in NotificationCenter removeObserver#5114
Merged
fix(Foundation): Fix deadlock in NotificationCenter removeObserver#5114
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Fix deadlock when calling
removeEventHandler()from another thread while also calling it from within an event handler (reactor thread).Problem
A deadlock occurred due to lock ordering inversion:
NotificationCenter::_mutex→NObserver::_mutexNObserver::_mutex→NotificationCenter::_mutexWhen Thread 1 called
removeObserver()holding_mutexand trying to calldisable(), while Thread 2 was innotify()holdingNObserver::_mutexand the handler calledremoveObserver(), both threads would deadlock.Solution
_pObjectatomic inNObserverandObserverto allow safe concurrent access without always requiring the mutexdisable()outside the lock inNotificationCenter::removeObserver()and destructorThe fix breaks the nested lock acquisition by releasing
NotificationCenter::_mutexbefore callingdisable().Changes
NObserver.h: ChangedC* _pObjecttostd::atomic<C*> _pObjectObserver.h: Same change (deprecated but still used)NotificationCenter.cpp: ModifiedremoveObserver()and destructor to calldisable()after releasing the lockFixes #4970