“多线程” iPhone 应用程序中的 NSTimers

发布于 2024-09-01 01:46:54 字数 279 浏览 2 评论 0原文

假设我的 iPhone 应用程序中有两个 NSTimer:timer1timer2timer1 每秒调用 function1 30 次,timer2 每秒调用 function2 30 次。假设这两个函数正在读取和更新相同的整数变量。这里有任何“多线程”问题吗?如果不是,iPhone OS 如何处理这两个函数的执行(一般而言)?

Say I have two NSTimers in my iPhone app: timer1 and timer2. timer1 calls function1 30 times per second and timer2 calls function2 30 times per second. Assume these two functions are reading and updating the same integer variables. Are there any "multi-threading" issues here? If not how does iPhone OS handle the execution of the two functions (in general)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

书间行客 2024-09-08 01:46:54

任何 iPhone 应用程序(以及其他一些平台)的核心都是运行循环。每个线程都可能有一个运行循环,主线程上的运行循环是为你设置的。当有事情要做时,例如触发 NSTimer 或绘制视图层次结构,运行循环会执行这些任务。当无事可做时,运行循环处于空闲状态,允许处理其他事情。

运行循环内部是线程感知的,因此运行循环不需要处理任何事情。所有 NSTimer 回调和视图渲染都发生在串行或线性流中的单个线程上。

具体细节可以查找NSRunLoop或者CFRunLoop。

The core of any iPhone application (and some other platforms) is a run loop. Each thread may have a run loop, and the run loop on the main thread is set up for you. When there is something to do, like fire an NSTimer or draw the view hierarchy, the run loop performs those tasks. When there is nothing to do, the run loop is idle, allowing other things to process.

The run loop internals are thread aware so that nothing handled by the run loop has to be. All the NSTimer callbacks and view rendering happens on a single thread in a serial or linear flow.

For specific details, you can look up NSRunLoop or CFRunLoop.

女皇必胜 2024-09-08 01:46:54

据我所知,NSTimers 使用运行循环来实现“异步”。如果计时器是使用 ScheduledTimerWith... 方法创建的,那么它将被安排在默认(主)运行循环上,并在主线程上执行。

我认为不会为计时器创建任何新线程(除非您显式执行此操作,并将计时器分配给该运行循环)。

所以最后,我相信你的两个计时器不应该互相冲突。

然而,文档指出计时器并不代表实时。计时器将在预定时间或之后触发,但不能保证准确地在预定时间触发。因此,如果触发的方法的执行时间比计时器的时间间隔长,您可能不会看到该方法像您期望的那样被调用。

话虽如此,您问这个问题有什么特殊原因吗?使用此设置您是否看到了不良行为?

As far as I'm aware, NSTimers use the run loop to achieve their 'asynchronosity'. If the timer is created using the scheduledTimerWith... method then it will be scheduled on the default (main) run loop and will be executed on the main thread.

I don't think any new threads are created for the timer (unless you do it explicitly, and assign the timer to that run loop).

So in the end, I believe your two timers shouldn't conflict with each other.

However, the documentation states that timers don't represent real time. The timer will fire on or after the scheduled time, but is not guaranteed to fire exactly at the scheduled time. Therefore if the fired method takes longer to execute than the interval of the timer, you may not see the method called as often as you'd expect.

With that said, is there any particular reason you're asking the question? Are you seeing undesired behaviour using this setup?

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