Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@synchronized() and NSLock differences

I have a block of code that is accessed frequently and from either the main thread or several other background threads. I need to ensure that this code only gets processed one at a time.

I'm currently using a @synchronized(self) { } block but I'm not sure if that's providing the correct protection. How does it differ from an NSLock instance?

Finally, can anyone suggest how I can protect my method? The method is in my application delegate, and I access it from various threads by calling:

[[[UIApplication sharedApplication] delegate] myMethod]; 

Many thanks,

Mike

like image 320
Michael Waterfall Avatar asked Nov 21 '09 17:11

Michael Waterfall


1 Answers

There is a great Blog post on the Google Mac blog about the inner workings of @synchronized:
http://googlemac.blogspot.com/2006/10/synchronized-swimming.html

I'm currently using a @synchronized(self) { } block but I'm not sure if that's providing the correct protection. How does it differ from an NSLock instance?

There are several ways to synchronize critical sections (@synchronized, NSLock, OSSpinLock, ...).
I think @synchronized is the most convenient (and also the slowest) approach.
Here is a good SO answer that explains the differences between @synchronized and NSLock.

You are accessing your method over a shared instances (which basically is a singleton) delegate. Maybe you can rethink your design and figure out a way that allows you to lock a smaller piece of code within myMethod.

like image 54
Thomas Zoechling Avatar answered Sep 20 '22 21:09

Thomas Zoechling