Reputation: 3921
I have two threads that access the same set of properties, but one only reads from the properties, the other one only writes to the properties.
Which of the following properties would need to be synchronized for read operations, and which would have to be synchronized for write operations?
@property (nonatomic) int myInt;
@property (nonatomic) NSInteger myInteger;
@property (nonatomic) CGImageRef cgImage;
@property (nonatomic, strong) UIImage *image;
@property (nonatomic, strong) NSMutableArray *array;
@property (nonatomic, strong) UIViewController *controller;
My first instinct is that everything needs to be synchronized for all read and write operations all the time. However, since one thread is always writing and one is always reading, I'm unsure of myself. Sure, always synchronizing is "safe" since I am unsure, but I was wondering what is actually correct?
For some reason, I have this feeling that maybe myInt and myInteger don't need to be synchronized for reads and writes since they are pass by value....?
Upvotes: 1
Views: 640
Reputation: 104698
well, this is what atomic properties are good at. if they were all atomic, then you could read and write without getting partially written results.
however, i've never found atomic objc properties truly useful in concurrent programs. i always result to regular locking, immutability, and so on.
although you could use atomics, it just doesn't get you very much in practical cases. they make your programs more thread resistant (not safe) at execution cost (both are bad, btw).
btw, pass by value is really not an issue here.
mutating a mutable value or object (e.g. reading and writing from that NSMutableArray from two threads), and maintaining the integrity of ivars which rely on each other are the primary problems.
example of maintaining the integrity of two ivars which rely on each other:
say you have two atomic properties of int type (day,month), and they have accessors. you would need more than atomics to avoid reading an invalid date (e.g. February 31st), if the reads and writes were happening from separate threads. the only way to really ensure your object is not in the middle of a partial update is to use synchronization primitives or immutable data -- this is ground atomic properties cannot save you from.
so the short answer is 'atomics', but objects in concurrent contexts are rarely so simple that the middle ground of atomics is truly thread safe.
Upvotes: 4