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

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

我在想,在处理不可变对象(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
}

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

  1. 使用的属性是 原语;
  2. 使用的属性是 保证是不可变的,而不是 指向可变对象(例如 的 NSStringNSArray 不可变对象(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/

相关文章:

iphone - 如何为 iOS 应用程序创建自定义错误域?

ios - ios可点击区域圆角矩形

iphone - UILocalNotification - 通知不显示

ios ScrollView 清空空白区域不滚动

java - 如何从不同的线程将条目填充到 map 中,然后从单个后台线程迭代 map 并发送?

c++ - 仿函数的线程与解构

iphone - 如何使带有 SLComposeViewController 的 presentViewController 更快?

iphone - iPhone 应用程序的技术架构图

objective-c - 如果我在一对多关系中添加相同的 NSManagedObject 几次会发生什么?

java - 如何在仅使用单个线程的情况下在 RxJava 中递归?