iPhone "multi-threading" question
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 m开发者_StackOverflow社区any months of development and incremental testing and I've never run into any problems.
Cheers!
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.
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.
精彩评论