iPhone“多线程”问题

发布于 2024-08-31 19:57:34 字数 260 浏览 5 评论 0原文

我有一个简单的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小草泠泠 2024-09-07 19:57:34

如果您的 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 of xPosition to a local variable in the game loop and only reference this variable for each run through the loop.

魔法少女 2024-09-07 19:57:34

如果仅在加速度计线程中更新,那么就不会有太大问题。最坏的情况是渲染线程看不到加速计线程对数据的更改。由于您在单个处理器上运行,因此这种情况不太可能发生。如果您在源代码中将变量标记为“易失性”,则可以解决后一个问题。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文