Is the lock really needed in my iPhone app?

I am working on a relatively simple iPhone application that has a multi-channel timer with many settings, such as the number of rounds and the round length. We allow certain settings to be made while the timer is running, which means that the timer can read from the same memory as the parameter records. There are no critical sections of code in which several threads are executed simultaneously, but the code from the settings may try to write the memory with which the timer counts.

In terms of a simple example, suppose we are a global variable foo and there is an NSTimer method that looks like this:

- (invalid) timerTick {NSString * x = foo; }

then in the settings code we do this while the timer is running:

foo = @ "test";

Is it enough to make foo atomic in this application, or do we need some sort of locking scheme?

Thanks.

+4
source share
2 answers

Usually you do not need to block when you use NSTimer usual way.

In more detail, when you create a timer with NSTimer scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: resulting timer is added to the thread start loop in which you create the timer. That way, if you create an NSTimer instance in the main thread this way, the timer starts being processed as part of the main event loop, so the callback you registered is called in the main thread, and not in another thread. Thus, if you do not create a single thread yourself, do not worry about blocking, etc.

See this for more details.

+4
source

You can either sync @synchronized or NSLock / NSRecursiveLock / NSConditionLock, which you read and write. Better to use standard methods to do this than to risk prematurely posting zero foo.

0
source

Source: https://habr.com/ru/post/1299403/


All Articles