I’m working on a relatively simple iPhone application that has a multi-round Timer with a number of settings such as the number of rounds and round length. We allow certain settings to be upated while the timer is running which means the timer may be reading from the same memory that the settings are writing. There are no critical sections of code where multiple threads will be executing at the same time but code from the settings may be trying to write memory the timer is reading from.
In terms of a simple example, let’s say we a global variable foo and there is an NSTimer method which looks as follows:
-(void)timerTick
{
NSString *x = foo;
}
then in the settings code, we do this while the timer is running:
foo = @”test”;
Will it be enough to make foo atomic in this application or do we need some kind of locking scheme?
Thanks.
Usually you don’t have to lock when you use
NSTimerin the usual way.In more detail, when you create the timer with
NSTimer‘sscheduledTimerWithTimeInterval:target:selector:userInfo:repeats:, the resulting timer is added to the run loop of the thread in which you create the timer. So, if you create theNSTimerinstance on the main thread this way, the firing of the timer is handled as a part of the main event loop, so the callback you registered is called on the main thread, not on another thread. So, if you don’t create any thread yourself, there’s no concern at all about locking etc.For more details, read this.