Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top