0

I have an NSMutableArray that's accessed primarily by the main thread in my iOS game. Every 2-3 seconds I need to perform an expensive operation on this grid. I don't need to modify the grid. I just need to do some calculations and return a result. How can I efficiently and safely use the grid in a background thread?

So far I've considered just copying the grid and passing it as the object in performSelectorInBackground. However this seems potentially wasteful. I've also considered just accessing the grid's reference from the background thread and making sure the main thread doesn't write to the grid until the background thread has finished processing. However this feels risky and I'm not sure if it's a common practice.

SundayMonday
  • 19,147
  • 29
  • 100
  • 154
  • Why are you [reposting this](http://stackoverflow.com/questions/13000608/running-expensive-calculations-in-the-background-objective-c) (or why did you delete it in the first place)? The links I gave you there still apply: [Locking NSMutableArray](http://stackoverflow.com/questions/11890522/locking-nsmutablearray) and the [Concurrency Programming Guide](http://developer.apple.com/library/mac/documentation/General/Conceptual/ConcurrencyProgrammingGuide/). – jscs Oct 22 '12 at 02:33
  • @JoshCaswell I think this version of the question is more specific. Also I added the approaches I've considered so far. – SundayMonday Oct 22 '12 at 02:39
  • 1
    In that case you should have edited your previous question, not deleted it. Having enough rep to even edit other people's posts, you really should know this. – BoltClock Oct 22 '12 at 15:23

1 Answers1

0

It all depends on if the game is going to have to stop / slow down if it can't write to the grid. If it does, then it defeats the purpose of running it in the background. If the game can continue fine without writing to the grid then that is the best option. It isn't dangerous as long as you make sure it doesn't write until the background processing is done.

If the game is going to be slowed down then I would go the copy route.

Both of these things can be handled directly in the grid class (if that is where you are doing the processing). You can have a way to "lock" the grid and you can have the grid object queue up changes until the processing is done. When the processing is done you can loop through all the operations and apply them. This way everything can continue as normal even if the grid is locked.

drewag
  • 93,393
  • 28
  • 139
  • 128