views:

90

answers:

2

I have a simple iPhone game consisting of two "threads": the main game loop where all updating and rendering happen 30 times per second (NSTimer)... and the "thread" that calls the accelerometer delegate 100 times per second. I have a variable "xPosition" that's updated in the accelerometer delegate function and used in the game loop. Is there a possibility of the two "threads" trying to use xPosition at the same time (hence causing a crash or some other problem). If so how can I fix this w/ minimal impact to the game's performance?

I've been using this set-up for many months of development and incremental testing and I've never run into any problems.

Cheers!

+1  A: 

If it's only updated in the accelerometer thread, then there's not much problem. Worst case is that the render thread won't see the change to the data by the accelerometer thread. Since you're running on a single processor, that's not likely to happen. That latter problem can be addressed if you flag the variable as 'volatile' in the source code.

Will Hartung
+2  A: 

If your NSTimer task and your game loop are both run from the main thread you will not encounter any problems with this since only one of them will execute at the same time. Additionally none of them can preempt the other.

However if you are using different threads, you have to be careful when using the xPosition in the game loop since it's value might be updated at any time from the other thread - even though there is only one processor. One simple way of getting past this would be to assign the value of xPosition to a local variable in the game loop and only reference this variable for each run through the loop.

Claus Broch
It sounds like he's just using a vanilla NSTimer and the accelerometer delegate callbacks, so everything he's doing should be running on the main thread. There will be no conflicts with that.
Brad Larson
that is exactly what I'm doing
MrDatabase