There is one thing I am not sure about when it comes to locks. I’ve read http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Multithreading/ThreadSafety/ThreadSafety.html#//apple_ref/doc/uid/10000057i-CH8-SW16 but one thing I am not sure about; does @synchronize (or just mutex in general) protect only a section of code (say inside a method) or lock the entire object as a whole?
For example, two threads working on these methods, which modify an array;
@synthesize m_myMutableArray;
-(void)threadA
{
@synchronized(m_myMutableArray) {
[m_myMutableArray removeAllObjects];
}
}
-(void)threadB
{
NSInteger asdf = 1;
@synchronized(m_myMutableArray) {
[m_myMutableArray addObject:asdf];
}
Does @synchronized not do anything because they are two separate blocks of code, or is it the same mutex being locked in both methods, meaning m_myMutableArray is threadsafe?
Thanks
The “argument” to
@synchronizedis a so-called token or key so you can have different locked sections. They only block each other when they have the same token. The object themselves are not “locked”.So if you have two
@synchronized(foo)and two@synchronized(bar), the foo sections block each other but will not block the bar sections.If possible, you should avoid
@synchronizedas it’s very slow, due to its dynamic nature.