Saturday, January 4, 2014

When dealing with property declarations, what is the difference between atomic and non-atomic?

atomic -Atomic means only one thread access the variable.Atomic is thread safe,but it is slow in performance.atomic is default behavior.Atomic accessors in a non garbage collected environment (i.e. when using retain/release/autorelease) will use a lock to ensure that another thread doesn't interfere with the correct setting/getting of the value. atomic it is not actually a keyword.

Ex: @property (retain) NSString *name; 
 
nonatomic -Nonatomic means multiple thread access the variable. Nonatomic is thread unsafe,but it is fast in performance.Nonatomic is NOT default behavior,we need to add nonatomic keyword in property attribute.It may result in unexpected behavior, when two different threads access the same variable at the same time.

Ex: @property (nonatomic,retain) NSString *name; 

Explain:
Suppose there is an atomic string property called "name", and if you call [self setName:@"A"] from thread A, call [self setName:@"B"] from thread B, and call [self name] from thread C, then all operation on different thread will be performed serially which means if one thread is executing setter or getter, then other threads will wait. This makes property "name" read/write safe but if another thread D calls [name release] simultaneously then this operation might produce a crash because there is no setter/getter call involved here. Which means an object is read/write safe (ATOMIC) but not thread safe as another threads can simultaneously send any type of messages to the object. Developer should ensure thread safety for such objects.

If the property "name" was nonatomic, then all threads in above example - A,B, C and D will execute simultaneously producing any unpredictable result. In case of atomic, Either one of A, B or C will execute first but D can still execute in parallel.

No comments:

Post a Comment