Search code examples
swiftconcurrencygrand-central-dispatchnsoperationqueue

Is there a way we might face race condition when running async tasks on serial queue


Suppose if multiple async tasks running in a serial queue are accessing a same shared resource, are there any chances we might face race condition?


Solution

  • Following the comment I've added, this is taken from Apple doc. In bold I put the emphasis to what you are looking for.

    Serial queues (also known as private dispatch queues) execute one task at a time in the order in which they are added to the queue. The currently executing task runs on a distinct thread (which can vary from task to task) that is managed by the dispatch queue. Serial queues are often used to synchronize access to a specific resource.

    If you are using a concurrent queue instead you could have a race condition. You can prevent it using dispatch barriers, for example. See Grand Central Dispatch In-Depth: Part 1/2 for more details.

    For NSOperation and NSOperationQueue the same applies. NSOperationQueue can be made serial with maxConcurrentOperationCount set to 1. In addition, using dependencies through operations, you can synchronize the access to a shared resource.