什么情况下原子属性有用?

时间:2011-01-14 21:06:16

标签: iphone objective-c multithreading cocoa properties

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:不可变属性

我在想,在处理不可变对象时,原子属性可能对避免锁有用,但由于不可变对象可以指向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
}

我能想到的唯一场景是,在没有锁的情况下使用原子访问器是安全的(因此值得使用原子属性):

  1. 使用属性 原语;
  2. 使用属性 保证是不可变的而不是 指向可变对象(例如 NSStringNSArray 不可变对象)。
  3. 我错过了什么吗?有没有其他充分理由使用原子属性?

1 个答案:

答案 0 :(得分:6)

你没有遗漏任何东西; atomic的用处主要限于您需要从多个线程访问或设置特定值的情况,其中该值也是整数

除了单个值之外,atomic不能用于线程安全目的。

我在weblog post a while ago中写了很多关于它的内容。

这个问题也是What's the difference between the atomic and nonatomic attributes?

的[非常好的]副本
相关问题