简体   繁体   English

在ObjC ++中原子属性线程安全吗?

[英]Is atomic property thread safe in ObjC++

据说在ObjC中使用“原子的”属性是线程安全的,但是我想知道在带有pthread的ObjC ++中是否仍然如此。

First of all: No, it is not said that "atomicity" is thread-safety neither in general nor for declared properties, neither in Objective-C nor in C++. 首先:不,无论是在Objective-C还是在C ++中,无论是一般还是声明的属性,都没有说“原子性”是线程安全的。 Atomicity means that no getter or setter (it is on object level, so even accessors of other properties) run simultaneously. 原子性意味着没有getter或setter(它是在对象级别,因此甚至其他属性的访问器)也不会同时运行。 But it says nothing of what happens immediately after setting or getting a value. 但是它并没有说明设置或获取值后立即发生的事情。 To have thread-safety you have to do more. 要具有线程安全性,您必须做更多的事情。 (Therefore atomicity of declared properties are akin of meaningless.) In the past atomic/nonatomic had more to do with memory management. (因此,声明属性的原子性毫无意义。)过去,原子/非原子与内存管理有更多关系。 This became less important by far since we have ARC. 自从有了ARC之后,到目前为止,这已变得不那么重要了。

After this, it is probably less important to answer to your Q: It is not documented, but has been documented a bit more in past. 在此之后,回答您的问题可能不太重要:它没有记录在案,但在过去已有更多记录。 Apple said that they used an object level lock. 苹果表示,他们使用了对象级锁。 Since even very simple NSLock uses pthreads internally – that's documented –, I assume that they work, if you created the threads with pthread. 由于即使很简单的NSLock也会在内部使用pthread(已记录),因此,如果您使用pthread创建线程,则我认为它们可以工作。


A little sample: 一些样本:

@interface Person
@property NSString *fristName;
@property NSString *lastName;
@end

@implementation Person
@end

Control flow 1: 控制流程1:

person.firstName = @"Chris";
person.lastName = @"Kienle";

Control flow 2: 控制流程2:

person.firstName = @"Amin";
person.lastName = @"Negm";
…
NSString *combined = [NSString @"%@ %@", person.firstName, person.lastName];

Possible result with perfect atomic and thread-safe accessors: 完美的原子和线程安全访问器可能产生的结果:

Christian Negm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM