Reputation: 145
I was asked during a technical interview this following question that confused me:
if there is an atomic NSMutableArray that being modified by two different threads. What are the risks for that scenario? Would that cause a crash? and how to avoid them?
Can anyone tell me why there would be any risks? atomic is a thread safe isn't it?
Thanks
Upvotes: 0
Views: 305
Reputation: 3439
The atomic
property attribute does not refer (directly) to thread safety. It refers to the fact that the compiler will synthesize the ivar and getter/setter methods. If you want to provide your own getter/setter, for example, you mark the property as nonatomic
and then write your getter/setting; the compiler will not generate an ivar.
Atomic property mutations are generally thread safe, but that's largely a side effect of modern CPUs. For example, setting an array property with a new object reference is generally thread safe. In other words, if two threads are setting a reference property at the same time exactly one will succeed; you won't end up with a weird half-reference that points off into space.
However, simply because the reference to an object is thread safe it does not make the object it refers to thread safe.
As a rule, any mutable object must use semaphores or some similar technique to safely mutate its state from multiple threads (or arrange that all access be performed from the same thread).
By far the simplest is to use semaphores. Surround or wrap any code that modifies or accesses the object with code that holds a semaphore until the operation is finished:
@implementation SafeCollection
{
NSLock* collectionLock;
NSMutableArray* collection;
}
- (void)addToCollection:(id)obj
{
[collectionLock lock];
[collection addObject:obj];
[collectionLock unlock];
}
- (id)objectInCollectionAtIndex:(NSUInteger)index
{
[collectionLock lock];
id obj = collection[index];
[collectionLock unlock];
return obj;
}
Thread safety is an expansive and complex topic, but the basics for two threads attempting to manipulate a mutable resource are pretty straight forward.
Upvotes: -1