• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Locking/synchronization conundrum
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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


  • Follow-Ups:
    • Re: Locking/synchronization conundrum
      • From: Derrick Bass <email@hidden>
  • Prev by Date: How to find out if a TCP port is in use?
  • Next by Date: Re: NSImage get / set Pixels
  • Previous by thread: Re: How to find out if a TCP port is in use?
  • Next by thread: Re: Locking/synchronization conundrum
  • Index(es):
    • Date
    • Thread