在什么情况下原子属性有用? [英] Under what circumstances are atomic properties useful?
问题描述
Objective-C属性默认为 atomic
,这可确保访问者是原子的,但不能确保整体线程安全性(根据这个问题)。我的问题是,在大多数并发场景中,原子属性不是多余的吗?例如:
Objective-C properties default to atomic
, which ensures that accessors are atomic but doesn't ensure overall thread-safety (as per this question). My question is, aren't atomic properties redundant in most concurrency scenarios? For example:
场景1:可变属性
@interface ScaryMutableObject : NSObject {}
@property (atomic, readwrite) NSMutableArray *stuff;
@end
void doStuffWith(ScaryMutableObject *obj) {
[_someLock lock];
[obj.stuff addObject:something]; //the atomic getter is completely redundant and could hurt performance
[_someLock unlock];
}
//or, alternatively
void doStuffWith(ScaryMutableObject *obj) {
NSMutableArray *cachedStuff = obj.stuff; //the atomic getter isn't redundant
[_someLock lock];
[cachedStuff addObject:something]; //but is this any more performant than using a nonatomic accessor within the lock?
[_someLock unlock];
}
场景2:不可变属性
我在想,在处理不可变对象时,原子属性可能对避免锁有用,但由于不可变对象可以指向Objective-C中的可变对象,所以这并不是很多帮助:
I was thinking that maybe atomic properties would be useful for avoiding locks when working with immutable objects, but since immutable objects can point to mutable objects in Objective-C, this isn't really much help:
@interface SlightlySaferObject : NSObject {}
@property (atomic, readwrite) NSArray *stuff;
@end
void doStuffWith(SlightlySaferObject *obj) {
[[obj.stuff objectAtIndex:0] mutateLikeCrazy];//not at all thread-safe without a lock
}
我能想到的唯一可以安全使用原子的场景没有锁的访问器(因此值得使用原子属性)是:
The only scenarios I can think of where it's safe to use atomic accessors without a lock (and therefore worth using atomic properties at all) are:
- 使用
primitives的属性; - 使用
保证不可变的属性而不是
指向可变对象(例如
和NSString
或$ code>
不可变对象的NSArray 。
- Working with properties that are primitives;
- Working with properties that are
guaranteed to be immutable and not
to point to mutable objects (such as
an
NSString
or anNSArray
of immutable objects).
我错过了什么吗?有没有其他充分理由使用原子属性?
Am I missing something? Are there any other good reasons to use atomic properties?
推荐答案
你没有遗漏任何东西; atomic
的用处主要限于您需要从多个线程访问或设置特定值的情况,其中该值也是整数。
You aren't missing anything; atomic
's usefulness is largely limited only to situations where you need to access or set a particular value from multiple threads where that value is also integral.
超出单个值, atomic
不能用于线程安全目的。
Beyond a single value, atomic
cannot be used for thread safety purposes.
我在不久前发布的博客。
这个问题也是一个[非常好的]复制品原子和非原子属性之间有什么区别?
This question is also a [very well posed] duplicate of What's the difference between the atomic and nonatomic attributes?
这篇关于在什么情况下原子属性有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!