Reputation: 6589
Let's say we have a NSMutableArray for example on a singleton object. The singleton object can obviously be called from multiple different threads.
Let's say we need users of the singleton to be able to addObjects or removeObjects. Or perhaps we have a custom object that we need to both set and read.
What's the proper way to handle these cases? Should every thread-unsafe property on a singleton have it's own serial/concurrent queue, and then overwrite addObject and removeObject functions for the NSMutableArray, wrapping reads in dispatch_sync, and writes in either dispatch_async(to a serial queue) or dispatch_barrier_async(to a concurrent queue)?
1) Does every thread-unsafe property need its own queue? Or should it at least have one in terms of performance. If multiple properties shared the same queue, it would be slower than necessary.
2) In what cases is this thread protection unnecessary. Ever? Or should thread-unsafe properties always have their setters and getter overwritten.
Upvotes: 1
Views: 147
Reputation: 162712
1) Does every thread-unsafe property need its own queue? Or should it at least have one in terms of performance. If multiple properties shared the same queue, it would be slower than necessary.
Depends entirely on how frequently you are pounding on the serialized APIs. Start with a simple model and then move to more complex if needed.
And keep in mind that the implementation isn't necessarily limited to just adding queues at whim.
You could also use a multiple-reader, one writer model. That would involve keeping an NSArray*
copy of the mutable array's contents that the readers can simultaneously hit. If the mutable array's contents are changed, then you can (thread safety in mind) swap a new immutable copy of the mutable array for the existing NSArray *
(could be done with an atomic @property
or you could use a concurrent queue for all reads with a barrier for the swap operation).
Something like the above might make sense when either the array is relatively small (cheap copies) or there are many many times more reads than writes.
2) In what cases is this thread protection unnecessary. Ever? Or should thread-unsafe properties always have their setters and getter overwritten.
A mutable collection is always thread unsafe, even when operating in a "readonly" mode. Only immutable collections are thread safe.
So, yes, you need to make sure you serialize any operation that would cause a thread unsafe action.
Upvotes: 1