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

sho*_*sti 6 iphone cocoa multithreading properties objective-c

Objective-C属性默认为atomic,它确保访问器是原子的,但不能确保整体线程安全性(根据这个问题).我的问题是,在大多数并发场景中,原子属性是不是多余的?例如:

场景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];   
}
Run Code Online (Sandbox Code Playgroud)

场景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
}
Run Code Online (Sandbox Code Playgroud)

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

  1. 使用原始属性;
  2. 使用保证不可变的属性,而不是指向可变对象(例如一个NSString或一个NSArray不可变对象).

我错过了什么吗?有没有其他充分理由使用原子属性?

bbu*_*bum 6

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

超出单个值,atomic不能用于线程安全目的.

我刚才在一篇博客文章中写了很多关于它的文章.

这个问题也是一个[非常好的]重复的原子和非原子属性什么区别?