Reputation: 811
NSMutableArray
is not thread-safe, but I don't see why they can't be designed to be thread-safe as long as different indices are being manipulated simultaneously. E.g. Index 1 points an instance of class X and Index 2 to another instance. Isn't it efficient to allow these two objects to be manipulated at the same time? Is this allowed when I use GCD or do I need to use a dispatch barrier when I am changing objects pointed to by different indices?
Upvotes: 0
Views: 87
Reputation: 80821
Your array contains pointers to objects. Pointers are essentially signposts, pointing to where the objects are located in memory.
Now when you mutate an object, you don't actually touch any pointers to the that object. The object's location in memory is unaffected.
Therefore, from the array's point of view, nothing happens when you mutate the objects themselves in it, as the pointers remain unaffected. This means that mutating different objects in an array from different threads is perfectly safe.
Therefore, you are correct when you say it's more efficient to download your data in parallel into different objects in your array.
So long as you're not mutating the array itself (adding or removing objects) or mutating the same object concurrently, you'll be fine.
If you do need to mutate the array from multiple threads simultaneously, you are right in saying you should use a concurrent queue, with a barrier to write, and a standard dispatch to read. This will allow for multiple concurrent reads (which is perfectly safe) and will serialise writes with reads.
Upvotes: 1