Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Locking an instance variable in Objective-C

What should be the best way in an iOS app to prevent an instance variable from being changed by an object while another is using it? Should the use of @synchronized(self) directive be enough?

Thanks in advance

like image 828
AppsDev Avatar asked Mar 13 '13 12:03

AppsDev


2 Answers

If you want that an object is blocked so that no two threads use it at the same time then @synchronize is one way. But this does not make it thread-safe.

You can also use GCD(Grand Central Dispatch) for the same

like image 158
Anoop Vaidya Avatar answered Oct 22 '22 20:10

Anoop Vaidya


What should be the best way in an iOS app to prevent an instance variable from being changed by an object while another is using it?

A good old lock, such as pthread_mutex; you could also use an Objective-C wrapper of this (e.g. NSLock and NSRecursiveLock). @synchronized also falls into this category, but it is the highest level mechanism mentioned here.

Of course, superior concurrent solutions typically have more to do with changes to design, program flow, favoring immutability, and so on. There will still be cases where mutual exclusion/locking is preferred or required.

Unfortunately, pure ObjC/Cocoa are sorely lacking in this domain -- developing a highly efficient concurrent program using ObjC and Cocoa technologies alone is far more difficult than it should be (or needs to be).

Should the use of @synchronized(self) directive be enough?

For simple cases, it is adequate. It is an object level Recursive Lock.

However, it is quite slow, compared to other mutual exclusion options.

I don't think @synchronized has much going for it, apart from:

  • convenience for the developer to introduce (can have bad side-effects) and
  • symmetry (it ensures an unlock matches a lock), greatly reducing the probability of deadlock compared to alternatives (a very good attribute).

@synchronized is convenient, but because it has a high cost, it should be used judiciously.

like image 35
justin Avatar answered Oct 22 '22 21:10

justin