Search code examples
multithreadinggrand-central-dispatchnslock

What is the difference (advantage and disadvantage) between using DispatchGroup and NSRecursiveLock?


What is the difference (advantage and disadvantage) between using DispatchGroup and NSRecursiveLock?

It looks like they are doing exactly the same thing.


Solution

  • Locks and groups serve very different purposes. When dealing with a series of concurrent tasks:

    • A lock generally is used to prevent/block these tasks from simultaneously interacting with some shared, non thread-safe, resource.

    • A group is generally used for identifying when these concurrent tasks are all complete (regardless of the order in which they finished).

    For example, if processing a series of images in parallel, you might use a lock or similar mechanism to update some property (e.g. the array of the results), whereas the dispatch groups is used to know when all of these concurrent tasks are done.