Search code examples
iosmultithreadingcocoa-touchgrand-central-dispatch

I have a singleton that can be accessed on multiple threads, should each of its array have a separate dispatch queue?


Say I have a singleton, FruitManager that looks after fruits. It has 3 arrays inside, favoriteApples, favoritePeaches, and favoriteOranges. The singleton can be accessed on any thread where these arrays can be read/written to.

Conventionally I'd use a DispatchQueue here to help the Reader/Writer problem, where I'd allow for concurrent reads but use a dispatch barrier block to make sure only one write action occurs at a time.

My question is, should I have a DispatchQueue for each of the 3 arrays (3 queues total)? Or just 1 dispatch queue for the entire class that would effectively lock writes to favoritePeaches if favoriteApples is being written to?


Solution

  • In answer to the one reader-writer vs one for each collection, it probably doesn’t matter. But there are a few considerations:

    1. The only potential problem with only one reader-writer is that a block on one collection will block them all. So, if you’re doing anything computationally expensive in the synchronization of one or more of the collections, you might want a separate reader-writer for each so it doesn’t adversely affect the performance of the others.

      Then again, you never want to do anything computationally expensive with reader-writer pattern, anyway. The “writer” is an asynchronous barrier, so that means that it will block any subsequent “readers” until the write is done. And if accessing the readers from the main queue, that will adversely affect the performance on the main thread (or from wherever you’re reading).

      So, if it’s computationally expensive, you wouldn’t use reader-writer, anyway. (You’d probably want an asynchronous fetch method, breaking you out of the reader-writer pattern.) And if you’re not doing anything computationally expensive, then there’s little benefit to using separate reader-writer for each collection.

    2. Setting up multiple reader-writers is fine if the three collections are entirely independent (as your simple example might suggest). But if there are any dependencies between the three collections (e.g. you’re reading from one to update the other), the code as potential to quickly become a mess.

    So, bottom line, I’d lean towards a single reader-writer for the whole class for the sake of simplicity. But if you already have a thread-safe collection class that is using reader-writer (or any synchronization mechanism, for that matter) internally, then that it’s probably fine to use that within this class that has these three collections (as long as you don’t have any hairy dependencies between your three collections).


    Needless to say, the above applies to any object shared amongst multiple threads, not just to singletons. The fact that you happen to be using using a singleton is irrelevant to the question at hand.