views:

198

answers:

2

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)?

+1  A: 

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?

Jasarien
No I'm just curious :-)
MrDatabase
+4  A: 

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.

drawnonward