I have a question on thread safety while using NSMutableDictionary.
The main thread is reading data from NSMutableDictionary where:
- key is
NSString - value is
UIImage
An asynchronous thread is writing data to above dictionary (using NSOperationQueue)
How do I make the above dictionary thread safe?
Should I make the NSMutableDictionary property atomic? Or do I need to make any additional changes?
@property(retain) NSMutableDictionary *dicNamesWithPhotos;
NSMutableDictionaryisn’t designed to be thread-safe data structure, and simply marking the property asatomic, doesn’t ensure that the underlying data operations are actually performed atomically (in a safe manner).To ensure that each operation is done in a safe manner, you would need to guard each operation on the dictionary with a lock:
You should consider rolling your own
NSDictionarythat simply delegates calls to NSMutableDictionary while holding a lock:Please note that because each operation requires waiting for the lock and holding it, it’s not quite scalable, but it might be good enough in your case.
If you want to use a proper threaded library, you can use TransactionKit library as they have
TKMutableDictionarywhich is a multi-threaded safe library. I personally haven’t used it, and it seems that it’s a work in progress library, but you might want to give it a try.