In Objective C I'm using a NSMutableArray instance from various thread and I'm using @synchronized to make it thread safe. currently all my acces to this array are protected with a @synchronized block, even objectAtIndex: method. Nevertheless I wonder which methods call really need to be protected with @synchronized. do I need to protect read access ?
What would happens if 'ObjectAtIndex' is not protected and called at the same time that 'removeObject' ?
If all methods are protected by a @synchronized what about performance? (I'writing a tcp/udp game server and really don't want to overprotect these array if it would decrease perf or generate locks).
for example I suppose that the 'containsObject:' method will enumerate to find the object and that I should avoid a concurent call to 'removeObject:' in another thread.
Perhaps a good solution would be to have too different locks (for read and write access)...
Help and suggestion are welcome !
Thanks a lot.
Please find a sample code below to illustrate :
@interface TestClass : NSObject
{
NSMutableArray * array;
}
@end
@implementation TestClass
- (id)init
{
self = [super init];
if (self)
{
array = [NSMutableArray array];
}
return self;
}
-(id)objectAtIndex:(NSUInteger)index
{
@synchronized(array) **// IS IT USEFUL OR NOT ??**
{
return [array objectAtIndex:index];
}
}
-(void)removeObject:(id)object
{
@synchronized(array)
{
[array removeObject:object];
}
}
-(void)compute
{
@synchronized(array)
{
for (id object in array)
{
[object compute];
}
}
}
@end