@property (atomic, retain) NSArray *array;
I don't override a setter and a getter of the array. I could use @synchronized(array){} or @synchronized(self.array){}. As I knows all cases are correct, am I right?
Using @syncrhonized(obj)
just forms a lock so that other code synchronizing on obj
won't execute at the same time.
Atomic properties work by not allowing changes to be made while a property is being accessed; they provide implicit locking for access.
array = someObject.array; //locked
[array doSomething]; //no longer locked
You can't override getters and setters for atomic
properties, but using the @sycnronized
directive around the getter/setter should be sufficient.
@synthesize array=_array;
...
-(void)setArray
{
@synchronized(self)
{
_array = array;
}
}
-(NSArray *)array
{
NSArray *retVal;
@synchronized(self)
{
retVal = _array;
}
return retVal;
}
Honestly, unless you're doing some seriously multithreaded programming, atomic properties are unnecessary and just cause performance hits.
As you've phrased the question, both statements are equivalent as a matter of concurrency safety strategy.
Depending on the scale and how far you have completed work on your project, you may wish to consider an alternative strategy for thread-safety altogether.
Recently, Apple has made a point of recommending thread-safety-by-serialization rather than traditional blocking. In short, as contention increases, serialized access is far more efficient than blocking with @synchronize.
Rather than synchronize, consider setting up a GCD serial queue and queuing up access to resources shared across threads.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With