Locking/synchronization conundrum
Locking/synchronization conundrum
- Subject: Locking/synchronization conundrum
- From: Matt Gough <email@hidden>
- Date: Fri, 17 Mar 2006 16:35:17 +0000
I have an NSMutableDictionary in an object of mine. There is no
direct access to this dictionary from outside the class. However i
provide the methods in my class to allow the user to get and set
objects in the dictionary:
e.g
@interface MyFruitFinder :NSObject
{
@private
NSMutableDictionary* fruitMapper;
}
- (id)fruitForKey:(id)aKey;
-(void) setFruit:(id)fruit forKey:(id)aKey;
@end
@implementation MyFruitFinder
- (id)fruitForKey:(id)aKey
{
return [fruitMapper objectForKey:aKey]
}
-(void) setFruit:(id)fruit forKey:(id)aKey
{
[fruitMapper setObject:fruit forKey:aKey];
}
@end
I now want to make my class thread safe as far as the fruitMapper
dictionary goes. Now I could just do:
- (id)fruitForKey:(id)aKey
{
@synchronized(fruitMapper)
{
return [[[fruitMapper objectForKey:aKey] retain] autorelease];
}
}
-(void) setFruit:(id)fruit forKey:(id)aKey
{
@synchronized(fruitMapper)
{
[fruitMapper setObject:fruit forKey:aKey];
}
}
The problem with this though is that it prevents multiple threads
calling fruitForKey: even if no-one is trying to call
setFruit:forKey. I only need to prevent more than one thread at a
time accessing the dictionary if one (or more) of them is trying to
modify it using setFruit:forKey:.
Is there a general solution to this problem?
Matt Gough
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden