Note that there are some explanatory texts on larger screens.

plurals
  1. PONSMutableArray collection and @Synchronized blocks
    text
    copied!<p>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 ?</p> <p>What would happens if 'ObjectAtIndex' is not protected and called at the same time that 'removeObject' ? </p> <p>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). </p> <p>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.</p> <p>Perhaps a good solution would be to have too different locks (for read and write access)...</p> <p>Help and suggestion are welcome !</p> <p>Thanks a lot.</p> <p>Please find a sample code below to illustrate :</p> <pre><code>@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 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload