Objective-C 属性默认为 atomic
,这确保访问器是原子的但不确保整体线程安全(根据 this question )。我的问题是,在大多数并发场景中,原子属性不是多余的吗?例如:
场景 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:不可变属性
我在想,在处理不可变对象(immutable对象)时,原子属性可能有助于避免锁定,但由于不可变对象(immutable对象)可以指向 Objective-C 中的可变对象,所以这并没有多大帮助:
@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
}
我能想到的唯一可以在没有锁的情况下安全使用原子访问器的场景(因此完全值得使用原子属性)是:
- 使用的属性是 原语;
- 使用的属性是
保证是不可变的,而不是
指向可变对象(例如
的
NSString
或NSArray
不可变对象(immutable对象))。
我错过了什么吗?还有其他使用原子属性的充分理由吗?
最佳答案
您没有遗漏任何东西; atomic
的用处在很大程度上仅限于需要从多个线程访问或设置特定值的情况,该值也是整数。
除了单个值,atomic
不能用于线程安全目的。
我在 weblog post a while ago 中写了很多关于它的文章.
这个问题也是 What's the difference between the atomic and nonatomic attributes? 的[非常好的]副本
关于iphone - 原子属性在什么情况下有用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4695947/