31

May somebody tell me if it is ok to return from inside a @synchronized block?

For example:

    - (id)methodThatReturnsSomething:(BOOL)bDoIt
    {
        @synchronized(self) {      

             if(!bDoIt) return nil;
             ...
        }
    }

or should I unlock the block first (using NSLock instead)?

Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
Vassilis
  • 2,878
  • 1
  • 28
  • 43
  • 1
    Possible duplicate of [Returning from method inside a @synchronized block](http://stackoverflow.com/questions/2704400/returning-from-method-inside-a-synchronized-block) – Ayush Goel Jan 09 '17 at 04:08

1 Answers1

35

@synchronized will automatically take down its exception-handling context when you return, and relinquish the lock. So the code you've written is fine.

Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
  • 9
    +1 It's worth mentioning that this is pretty much *why* `@synchronized` exists – it relieves of you having to manually relinquish any locks of your own (which can get quite spaghetti-like with multiple code paths). – Justin Spahr-Summers Dec 27 '10 at 12:18
  • 3
    Answer with 27 votes from a no longer existing user is nice however would be nice to have the links to some authoritative sources. – Stanislav Pankevich Nov 14 '16 at 16:56