Objective-c properties for primitive types

后端 未结 3 484
生来不讨喜
生来不讨喜 2020-12-30 10:56

In Objective-C Does it ever make sense to specify a property for a primitive type as nonatomic?

I\'m wondering about the difference between these two pr

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-30 11:33

    In a x-bit architecture (eg: 32bit, 64bit, etc.) any value which is x or less bits will always be read or written atomically. This is a property of any sane hardware implementation.

    The default atomic property means that a property value is always set or get in whole, disregarding what other threads are doing. This is only a concern for properties that exceed the number of bits of the architecture. Nonatomic is completely ignored by the compiler on any other type.

    Example:

    @property struct { int d; } flag;
    @property (atomic) struct { float x; float y; } point;
    @property (atomic,copy) NSString *s;
    
    • struct { int d; } is already atomic so the accesors don't need mutual exclusion.

    • struct { float x, float y} could be in an inconsistent state if it wasn't atomic. Example: two threads setting {1,2} and {3,4} could overlap the writing, and the struct could end up with a value from each set: {1,4}.

    • Pointers are stored in a single memory position but they require several statements for memory management.

    Atomic properties contribute to thread safety avoiding race conditions that lead to inconsistent values or memory management mishaps. This alone doesn't guarantee thread safety because it doesn't deal with other problems like deadlock, starvation, visibility, etc.

提交回复
热议问题