简体   繁体   中英

iPhone SDK Nonatomic and Atomic

Really quick and simple question: In Objective-C what is the difference between nonatomic and atomic? like when declaring properties like "@property (nonatomic, retain) id object"?

The code for a non atomic retain getter and setter conceptually looks something like:

-(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:

-(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.

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.

In the atomic case, this can't happen because the getter puts the object in the thread's autorelease pool before returning it. 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.

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

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