简体   繁体   中英

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++. Atomicity means that no getter or setter (it is on object level, so even accessors of other properties) run simultaneously. 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.

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.


A little sample:

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

@implementation Person
@end

Control flow 1:

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

Control flow 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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