Locking an object from being accessed by multiple threads – Objective-C

Fold 1
Generally your understanding of what @synchronized does is correct. However, technically, it doesn’t make any code “thread-safe”. It prevents different threads from aquiring the same lock at the same time, however you need to ensure that you always use the same synchronization token when performing critical sections. If you don’t do it, you can still find yourself in the situation where two threads perform critical sections at the same time. Check the docs.

Fold 2
Most people would probably advise you to use NSRecursiveLock. If I were you, I’d use GCD. Here is a great document showing how to migrate from thread programming to GCD programming, I think this approach to the problem is a lot better than the one based on NSLock. In a nutshell, you create a serial queue and dispatch your tasks into that queue. This way you ensure that your critical sections are handled serially, so there is only one critical section performed at any given time.

Fold 3
This is the same as Fold 2, only more specific. Data base is a resource, by many means it’s the same as the array or any other thing. If you want to see the GCD based approach in database programming context, take a look at fmdb implementation. It does exactly what I described in Fold2.

As a side note to Fold 3, I don’t think that instantiating DatabaseManager each time you want to use the database and then releasing it is the correct approach. I think you should create one single database connection and retain it through your application session. This way it’s easier to manage it. Again, fmdb is a great example on how this can be achieved.

Edit
If don’t want to use GCD then yes, you will need to use some kind of locking mechanism, and yes, NSRecursiveLock will prevent deadlocks if you use recursion in your methods, so it’s a good choice (it is used by @synchronized). However, there may be one catch. If it’s possible that many threads will wait for the same resource and the order in which they get access is relevant, then NSRecursiveLock is not enough. You may still manage this situation with NSCondition, but trust me, you will save a lot of time using GCD in this case. If the order of the threads is not relevant, you are safe with locks.

Leave a Comment