How important is it to fix race conditions for sma

2019-09-13 18:15发布

问题:

I'm working on an iOS app and I've found some race conditions in my app for nonatomic BOOL and NSInteger properties. I was curious, does it really matter if these get fixed? Like, if I have a read and a write at the same time for a BOOL and I don't care whether it uses the old or new value of the BOOL, as long as it uses one of them, isn't that OK? I'd be surprised if a read could come up with 1 when the start and end values of the BOOL from the write are 0.

回答1:

This is a “benign” race, discussed in WWDC 2016 video Thread Sanitizer and Static Analysis (at about 14:40).

They point out that no race should be considered benign because:

  • It’s contingent upon the particular hardware architecture you are using, and you have no assurances that such a data race will continue to be benign under different architectures;

  • All data races (benign or otherwise) are considered to be an undefined behavior from C/C++ standards.

  • While this may not be an issue in your code, compilers are free to reorder instructions oblivious to what other threads might be doing, so in some cases, in the absence of some synchronization mechanism, it can lead to “very subtle bugs.”

Bottom line, even though it’s likely not essential to fix these benign races, Apple advises that you do so, regardless. Fortunately, since you’re dealing with Objective-C, it’s easily remedied by making the properties atomic.