简体   繁体   English

iPhone SDK非原子和原子

[英]iPhone SDK Nonatomic and Atomic

Really quick and simple question: In Objective-C what is the difference between nonatomic and atomic? 真正简单的问题:在Objective-C中,非原子和原子之间有什么区别? like when declaring properties like "@property (nonatomic, retain) id object"? 例如在声明“ @property(非原子,保留)id对象”之类的属性时?

The code for a non atomic retain getter and setter conceptually looks something like: 非原子保留getter和setter的代码在概念上看起来类似于:

-(id) foo
{
    return fooIvar;
}

-(void) setFoo: (id) newFoo
{
    [newFoo retain];
    [fooIvar release];
    fooIvar = newFoo; 
}

The code for an atomic getter and setter conceptually looks something like this: 原子getter和setter的代码在概念上看起来像这样:

-(id) foo
{
    @synchronized(self)
    {
        return [[fooIvar retain] autorelease];
    }
}

-(void) setFoo: (id) newFoo
{
    @synchronized(self)
    {
        [newFoo retain];
        [fooIvar release];
        fooIvar = newFoo;
    } 
}

The implementation details are different, notably the locking ismore light weight than synchronising the object with the ivar. 实现细节有所不同,特别是锁定比将对象与ivar同步要轻得多。

In the non atomic case and in a multithreaded environment, you can't guarantee that the getter will give you a valid object because between the getter returning the reference and the caller retaining it (or doing anything else) another thread could call the setter, releasing the object and possibly deallocating it. 在非原子情况下和多线程环境中,您不能保证getter会为您提供有效的对象,因为在getter返回引用和保留该引用的调用方(或进行其他操作)之间,另一个线程可以调用setter,释放对象并可能对其进行分配。

In the atomic case, this can't happen because the getter puts the object in the thread's autorelease pool before returning it. 在原子情况下,这不会发生,因为getter在返回对象之前将对象放入线程的自动释放池中。 If another thread calls the setter and releases the object before the caller has a chance to retain it, it doesn't matter because of the ownership the autorelease pool has. 如果另一个线程调用了setter并在调用者有机会保留它之前释放了该对象,则由于自动释放池具有所有权而没有关系。

非原子的-开销少,但不是线程安全的。

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

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