3

Using @synchronized directive on method body

-(void)testSynchronizeMethod:(int)value
{
    @synchronized(value)
    {
        int value1 = 100; //sample line 1
        int value2 = 120; //sample line 2
        [self calledMethod];
    }
}

//case 1
-(void)calledMethod
{
    NSLog(@"is @synchronized directive applied to this method");
    NSLog(@"what happens if I enclose this method with @synchronized directive");
}

**or**
//case 2
-(void)calledMethod
{
    @synchronized(value){
        NSLog(@"is @synchronized directive applied to this method");
        NSLog(@"what happens if I enclose this method with @synchronized directive");
    }
}

Q: In case 2 Are Two mutex locks created around '-(void)calledMethod'?

EDIT I'm getting a signal SIGINT on main thread while I'm using such mutex locks. I'm attaching a screen grab if someone could suggest me what is going wrong?enter image description here

Pranav Jaiswal
  • 3,752
  • 3
  • 32
  • 50
  • [How does @synchronized lock/unlock in Objective-C?](http://stackoverflow.com/questions/1215330/how-does-synchronized-lock-unlock-in-objective-c) – Parag Bafna Mar 01 '13 at 13:06
  • 2
    How can `@synchronized` work on an `int`??? – Hot Licks Mar 01 '13 at 13:07
  • @HotLicks ignore that. Just tested, and according to [this apple doc](http://examples.oreilly.com/9780596809775/ObjC.pdf) you are correct. My bad. – Richard J. Ross III Mar 01 '13 at 13:10
  • A SIGINT means that a thread was interrupted while waiting for something to complete, in this case to access your mutex. I would consider using dispatch callbacks instead of polling for data with @synchronized. – Richard J. Ross III Mar 01 '13 at 13:42
  • but according to apple documentation @synchronized handles all possible exceptions automatically for you? why doesn't this hold true for this exception? – Pranav Jaiswal Mar 01 '13 at 13:46

1 Answers1

4

Yes, and no at the same time. @synchronized is a recursive lock according to the docs, meaning that two mutex locks are created, but they don't cause a deadlock and are both destroyed properly.

One thing to note, however, is that this awesome 'recursive' locking is quite expensive, and another form of mutex (NSLock, NSConditionLock, etc.) should probably be used if the situation supports it.

@synchronized is an amazing keyword, don't get me wrong, but don't just go willy-nilly throwing it in places that don't need it.

Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201