简体   繁体   中英

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

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

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 (eg 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.

If the only purpose is to be able to access

self.myString; //getter

and,

self.myString=aString; //setter

The best way is to declare it as atomic, for example:

@property (atomic, strong) NSString* myString;

This will ensure that in a multithreaded environment, setting and getting myString by thread 1 is protected from thread 2 doing something to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM