Thread Safe Design

threadsThread safe design is achieved when operations on certain shared data structures can be safely executed from multiple threads at the same time. There are multiple ways to achieve thread safety using synchronisation tools provided by the iOS. They mostly consist of mutex locks (NSLock class or @synchronized directive) or the use of queues and GCD.

The example below shows thread safe implementation of Observer Pattern. It is a straightforward and clean implementation using an atomic property and @synchoronized directive for mutex lock. Atomic property does not guarantee thread safety (you’ll probably find many statements that it does), it guarantees that the object will be completely set or read when simultaneously accessed from multiple threads. Nonatomic property does not guarantee to return a valid object when accessed simultaneously from multiple threads. This guarantee comes with a price since there is a certain overhead to getters and setters of atomic properties. That is fine in many situations when the properties are not accessed (getter/setter) with a high frequency. To achieve thread safety it is a good idea to use immutable objects whenever possible since they are thread safe by default.

The example below shows the use of a queue and GCD to achieve thread safety of the Observer Pattern implementation. The idea is to use a concurrent dispatch queue and dispatch_barrier_async calls which ensures that the block does not execute concurrently with other blocks dispatched on that queue. The calls to observer objects execute concurrently.

If you liked this blog post I’d appreciate if you followed me on Twitter

Related Post

Remember to share...Share on FacebookTweet about this on TwitterShare on Google+Share on LinkedInEmail this to someone

Leave a Reply

Your email address will not be published. Required fields are marked *