I had issues with thread safety. I have a queue that when I modified the contents caused errors across threads. I hadn't used locks before, but thought I try. I added a lock around all code that manipulated the backing NSMutableArray for my queue. The issue, I think, is that I didn't use the same lock for all of them. I created a new instance of NSLock in each method that modified the array. I'm assuming I should use one NSLock ivar to protect the array. But my confusion comes from the fact that it worked once I added it. Below is a sample. I assume that everywhere that I created a new NSLock, I should have just used one ivar NSLock. I would think that this code just locked enqueues against other enqueues and the dequeues against other dequeues and not the enqueues against the dequeues. Clarification would be great.
@implmentation
...
- (void)enqueue:(id)obj
{
NSLock *arrayLock = [[NSLock alloc] init];
[arrayLock lock];
[_backingStore addObject:obj];
[arrayLock unlock];
}
- (id)dequeue
{
NSLock *arrayLock = [[NSLock alloc] init];
[arrayLock lock];
id result = [_backingStore firstObject];
if( result )
{
[_backingStore removeObjectAtIndex:0];
}
[arrayLock unlock];
return result;
}
...
@end