Fix Ordering on WordLock (tsan detected) #292
Merged
+24
−3
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.
I was writing some hand-rolled locks for a tutorial, and did some lightweight fuzzing of the locks under thread-sanitizer to check correctness. I used parking_lot::RawMutex as my "control group" to sanity-check my test suite, but it ended up detecting data races in WordLock.
Taking a look, the Orderings seem a bit too loose — lock_slow used Release in the cmpxchg_weak but needs at least Acquire semantics to acquire the lock (although just using Acquire did not appease TSan), and unlock_slow had a similar problem but reversed (although that code more obviously needs at least Acquire, and so makes sense that it needs AcqRel).
That said, I'm definitely not sure these are actually minimal orderings, but I wasn't able to reduce any individual ordering further without upsetting TSan. That said, there may also be a cleverer approach to this.
This is the code that detected the issue. I haven't minimized it, although its still pretty small. It uses
cobb
to perform the thread fuzzing, butcobb
is all safe code (aside from a single function that isn't called in this test, and just does volatile reads/writes that are clearly sound) https://gist.github.com/thomcc/6ca2bef4b7526caeda06f4cceaabfe70