gpt4 book ai didi

ios - Objective-C 中的原子属性与线程安全

转载 作者:IT王子 更新时间:2023-10-29 07:52:42 27 4
gpt4 key购买 nike

在我读过的大多数讨论中,它表明使属性成为原子属性并不能保证它是线程安全的,它只是保证返回的值不会因为一个对象写入而成为垃圾它和另一个试图同时阅读它。

我知道这不是线程安全的,因为第三个对象可能正在写入它,虽然访问它的对象不会返回垃圾,但不完全确定它会返回哪个值,因为多个对象正在写入它同时,它可能会获得它们的任何值。

所以当我们说它不会返回垃圾时,垃圾是否是指如果一个对象是非原子的并且一个对象试图访问它而另一个正在写入它,它可能会在中期返回结果写,而只得到写所带来的改变的部分、不完整的版本?这就是“垃圾”在这个意义上的意思吗?原子属性有助于防止什么?

最佳答案

Objective C 中的atomic 属性保证您永远不会看到部分写入。当 @property 具有属性 atomic 时,不可能仅部分写入该值。 setter 是这样的:

- (void)setProp:(NSString *)newValue {
[_prop lock];
_prop = newValue;
[_prop unlock];
}

所以如果两个线程要同时写入值@"test"@"otherTest",那么在任何给定时间,属性只能是属性的初始值或@"test"@"otherTest"nonatomic 速度更快,但该值是垃圾值并且没有 @"test"/@"otherTest" 的部分字符串(thx @Gavin)或任何其他垃圾值。

但是 atomic 仅在使用简单的情况下是线程安全的。它没有保证。 Appledoc说如下:

Consider an XYZPerson object in which both a person’s first and last names are changed using atomic accessors from one thread. If another thread accesses both names at the same time, the atomic getter methods will return complete strings (without crashing), but there’s no guarantee that those values will be the right names relative to each other. If the first name is accessed before the change, but the last name is accessed after the change, you’ll end up with an inconsistent, mismatched pair of names.

我在使用 atomic 时从来没有遇到过问题。我是这样设计代码的,原子属性没有问题。

关于ios - Objective-C 中的原子属性与线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21098494/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com