Is "atomic" required here?
A s开发者_如何学Cimple question regarding multhreading programming: I have an NSMutableArray instance variable that is read by the main thread and set by another thread. I'm currently using this:
@property (nonatomic, retain) NSMutableArray *locations;
But I assume I have to remove the "nonatomic" directive now?
If you create a new array and assign it to locations then yes the atomic attribute would be needed.
If you are going to be adding/removing location objects from the other thread then the atomic attribute on the array does not apply. The various NSMutable... collections are not thread safe because the add/insert/remove methods are not designed to be called from multiple threads.
See SO question: NSMutableDictionary thread safety
A better approach might be to have the other thread send the main thread an array of locations to add or remove so that the changes only happen on the main thread.
"nonatomic" is not thread safe. Check out this SO question:
iPhone SDK Nonatomic and Atomic
It most situations, you won't have a problem by leaving the property as nonatomic. I almost never need to use atomic and all of my applications use some sort of multithreading.
The correct approach IMO is to leave all properties atomic unless there is a demonstrable performance problem as revealed by profiling the code.
However, that won't help in this instance because making the property atomic does nothing to make the internal state of the NSMutableArray thread safe. You'll need to make the property atomic and introduce some sort of synchronisation to stop one thread from modifying the array (i.e. adding or removing objects) while the other is accessing it. As this is quite tricky to enforce, I probably wouldn't expose the array as a property at all. I'd have methods on the parent object something like:
-(void) addLocation: (id) newLocation;
-(id) locationAtIndex: (NSUInteger) index;
etc. analogous the the NSMutableArray methods and they'd all be synchronised. If there were a property that returned the whole array, it would be read only and would return an immutable copy of the real array.
精彩评论