只读属性总是“原子的"吗? [英] Is readonly property always "atomic"?

查看:50
本文介绍了只读属性总是“原子的"吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时我们有一个简单的只读属性,它的值可能会改变

Sometimes we have a simple readOnly Property whose value may change

@property (readonly) NSFetchedResultsController * FetchController;
@property (readonly) NSFetchRequest * FetchRequest;
@property (readonly) NSPredicate * KeywordPredicate;

我想当值改变时,它是通过某种简单的指针操作在眨眼间完成的.类似的东西

I suppose when the value change it's done on a blink of an eye through some sort of simple pointer manipulation. Something like

_FetchRequest = newFetchRequest;

实际变化的过程可能会有很大变化,但实际变化应该在这一行.

The actual process of changing may change a lot but the actual change should be on that one line.

问题是,这样简单的指针赋值总是原子的吗?如果那一行实际上由几行机器代码组成并且有人要求这些机器代码之间的属性呢?

The question is, is such simple pointer assignment always atomic? What about if that one line actually consist of several line of machine codes and somebody ask for the property between those machine codes?

最后的问题是指针上的简单赋值运算符是否总是原子的.

At the end the question is whether simple assignment operator on pointers is always atomic or not.

如果是这样,什么时候是原子的,什么不是?简单的赋值运算符对于复杂的对象当然不是原子的.

If so, when it is atomic and what's not? Simple assignment operators won't be atomic for complex objects of course.

那么,这些简单的单行赋值运算符是原子的,在多大程度上是原子的?对于指针和原始类型,会一直这样吗?

So to what extend those simple one line assignment operators are atomic? For pointers and primitive types, will it always be?

推荐答案

认为只读操作本质上是原子操作是一种常见的误解.不能保证.原子性保证线程安全也是一个常见的误解,但是是一个不同的主题.

It is a common misconception to consider read-only operations as atomic in nature. It isn't guaranteed. It is also a common misconception that atomicity guarantees thread safety, but that is a different subject.

在 readonly 属性上原子和非原子的区别在于 atomic(这是默认值,但未声明)保证从 readonly 检索方法返回的值是整数.

The difference between atomic and nonatomic on readonly properties is that atomic (which is the default, but not declared) guarantees that the value returned from the readonly retrieval method is integral.

即如果是对象,则保留并自动释放.如果它是结构体,则会使用适当的锁来确保返回结构体的整数值.

That is, if it is an object, it will be retained and autoreleased. If it is a struct, an appropriate lock will have been used to ensure an integral value of the struct was returned.

请注意,仅仅因为属性被公开声明为只读并不排除它被重新声明为内部使用的读写.因此,原子和非原子之间的差异可能非常显着;一个类可能会声明一个只读属性为非原子的同时记录该类上的所有 API 只能从一个线程使用.

Note that simply because a property is declared publicly readonly does not preclude it being re-declared as readwrite for internal use. Thus, the difference between atomic and nonatomic might be quite significant; a class might declare a readonly property as nonatomic while also documenting that all API on the class must be used from one thread only.

这篇关于只读属性总是“原子的"吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆