iPhone“多线程”问题
我有一个简单的 iPhone 游戏,由两个“线程”组成:主游戏循环,其中所有更新和渲染每秒发生 30 次 (NSTimer)...以及每秒调用加速度计委托 100 次的“线程”。我有一个变量“xPosition”,它在加速度计委托函数中更新并在游戏循环中使用。两个“线程”是否有可能同时尝试使用 xPosition(因此导致崩溃或其他问题)。如果是这样,我该如何解决这个问题并对游戏性能影响最小?
我已经使用这种设置进行了数月的开发和增量测试,并且从未遇到任何问题。
干杯!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的 NSTimer 任务和游戏循环都从主线程运行,您将不会遇到任何问题,因为它们中只有一个会同时执行。此外,它们中的任何一个都不能抢占另一个。
但是,如果您使用不同的线程,则在游戏循环中使用 xPosition 时必须小心,因为它的值可能随时从其他线程更新 - 即使只有一个处理器。解决此问题的一种简单方法是将 xPosition 的值分配给游戏循环中的局部变量,并且仅在每次循环运行时引用该变量。
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 ofxPosition
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.