Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the proper way of using @synchronized?

@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?

like image 330
Voloda2 Avatar asked May 08 '12 16:05

Voloda2


2 Answers

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.

like image 125
Ash Furrow Avatar answered Nov 15 '22 20:11

Ash Furrow


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.

like image 42
isaac Avatar answered Nov 15 '22 20:11

isaac