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
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
There are several ways to synchronize critical sections (@synchronized, NSLock, OSSpinLock, …).
I think
@synchronizedis 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.