Improve error checking in mutex stub #3167
Draft
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.
Change Description
Replace the stub implementation of Os::Mutex with a more complete nonblocking implementation that still avoids platform dependencies.
Rationale
The default mutex stub is intended to be usable on any platform, even platforms that do not have threads and cannot block. This stub is inappropriate for applications that need to contend over mutexes. However, if inadvertently used in applications in a way that would result in mutex contention, they would silently allow incorrect and dangerous behavior. (Notably, they allowed multiple threads to enter the same critical section.)
The new implementation still works on all platforms, and never blocks. However, it ensures that only one thread enters each critical section at a time. Attempting to acquire a mutex that is already taken will result in a failure to acquire the mutex, and likely an assertion. Because this should only occur in the case of a coding defect, this is an improvement over the previous implementation.
Testing/Review Recommendations
No specific testing has been performed yet, so I am leaving this PR as a draft for the moment.
Future Work
It is possible that some existing programs work correctly by luck but happen to rely on the ability to have multiple threads acquire the same mutex. These programs could be broken by this upgrade. Therefore, this change in behavior should be documented in the release notes.