Fix Possible Deadlock caused by Thread Explosion #1175
Merged
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.
Proposed changes
(Main changes are in common core: AzureAD/microsoft-authentication-library-common-for-objc#911)
There are reports that deadlock could happen in MSAL if too many threads are calling MSAL APIs at the same time.
After some investigation, we found that deadlock could happen if there are more than 64 threads calling MSAL APIs.
Root cause:
There is a limit regarding how many GCD threads we can create for an app (limit is 64 according to my testing, also found reference here https://www.oreilly.com/library/view/high-performance-ios/9781491910993/ch04.html). Such a limitation could cause deadlock in our code. E.g., if a
dispatch_barrier_async
block is at the front of a queue and waiting to be executed, it will block all otherdispatch_sync
blocks. Image there are 64 threads (limit is hit) waiting atdispatch_sync
, then no more thread can be created to execute thedispatch_barrier_async
block. In such a case, bothdispatch_barrier_async
anddispatch_sync
cannot proceed further. Deadlock occurs.Solutions:
dispatch_barrier_async
todispatch_barrier_sync
. The former requires a new thread to be created to execute the block, while the later tries to use the current thread to execute the block. In such a way we could avoid the "no more thread can be created" issue.Type of change
Risk
Additional information