修复小型图元的竞争条件有多重要? [英] How important is it to fix race conditions for small primitives?

查看:276
本文介绍了修复小型图元的竞争条件有多重要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个iOS应用程序,并且在我的应用程序中发现了一些非原子的BOOLNSInteger属性的竞争条件.我很好奇,如果解决这些问题真的很重要吗?就像,如果我同时对一个BOOL进行读取和写入,并且我不在乎它是否使用BOOL的旧值或新值,只要它使用其中一个,就可以了.可以吗?如果写入时BOOL的起始值和结束值均为0,那么如果读取结果为1,我会感到惊讶.

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.

推荐答案

这是一次良性"竞赛,在WWDC 2016视频

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;

所有数据竞赛(良性或其他)都被认为是C/C ++标准中未定义的行为.

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."

最重要的是,即使不一定要解决这些良性竞赛,Apple还是建议您这样做.幸运的是,由于您使用的是Objective-C,因此可以通过将属性设置为atomic来轻松地对其进行补救.

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.

这篇关于修复小型图元的竞争条件有多重要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆