• 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
Re: Locking from within an enumerator
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Locking from within an enumerator


  • Subject: Re: Locking from within an enumerator
  • From: Scott Thompson <email@hidden>
  • Date: Tue, 20 Apr 2004 20:41:33 -0500

I have a data model that can be accessed by multiple threads at once. It is basically an array of stuff. I want to be able to allow threads to iterate over the data model, and so I was thinking of creating an NSEnumerator subclass that locks the model for the duration of the enumerator's life. The problem with this is that I don't know when the NSEnumerator will have its dealloc called (actually, I don't even know if dealloc is really ever called - I put NSLogs in - (void) dealloc before, but the NSLogs never print out).

Anyway, back to the main point, assuming dealloc is eventually called, I'm not sure if I can depend on that behavior to call unlock for me.

Does anyone have a better obj-c design pattern for iterating over an array in a multithreaded environment?

Well, one common method would be to make a copy of the array and iterate over the copy... something like:

/* Grab a Mutex lock that controls access to the array */
ThisCodeGrabsAMutexLock();

Array *copyArray = [NSArray arrayWithArray: arrayToCopy];

/* release the mutex */
ThisCodeReleasesTheMutexLock()

return [copyArray objectEnumerator];

Given moderately sized arrays, creating the array copy is pretty fast because it just increases the reference counts on all the objects in the array. Assuming you've set up an autorelease pool for your thread, both the copy of the array and the object enumerator will be autoreleased. Plus, rather than being locked out for the entire duration of the iteration, your array will only be locked out long enough for a copy to be made of it.

Scott
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives: http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.


  • Follow-Ups:
    • Re: Locking from within an enumerator
      • From: "Mike R. Manzano" <email@hidden>
References: 
 >Locking from within an enumerator (From: "Mike R. Manzano" <email@hidden>)

  • Prev by Date: Re: Abbreviated-Keyword Dictionary Search possible?
  • Next by Date: Re: Enabling NSMenuItem in Code?
  • Previous by thread: Locking from within an enumerator
  • Next by thread: Re: Locking from within an enumerator
  • Index(es):
    • Date
    • Thread