Primitive types do not guarantee that they can be partially modified, because modifications to primitive types are not guaranteed to be atomic in C and Objective-C are inherited from there. C guarantees only points in the sequence and does not require that the processing between two points in the sequence be atomic - the rule is that each complete expression is a point in the sequence.
In practice, modifying primitives is often a two-step process; modification is made in the register and then written to memory. It is very unlikely that the record itself will not be atomic, but there is also no guarantee when it will occur in comparison with the modification. Even with volatile qualifications, the only guarantees are provided in terms of sequence points.
Apple provides some C functions for atomic activities through OSAtomic.h , which are directly mapped to specialized atomic instructions offered by CPUs for implementing concurrency mechanisms. Perhaps you could use one of them more directly than through a crazy mutex.
Common patterns in Objective-C:
- immutable objects and functional transformations - there are also reasons for memory management, but partly why
NSString , NSArray , etc., in particular, differ from NSMutableString , NSMutableArray , etc. - serial mail queues, which can be combined with copy-modification-replacement, copying in the queue, going to another place to change, and then return to the queue for replacement;
- such
@synchronized s, NSConditionLock or other explicit synchronization mechanisms that are appropriate.
The main thread itself is a sequential dispatch queue, so you can completely ignore the concurrency problem if you limit yourself.
source share