DEV Community

Bibin Jaimon
Bibin Jaimon

Posted on • Updated on

Serial DispatchQueue | sync & async explained | Swift

Doc: DispatchQueue

The serial queue process a block of object one at a time. There will be an order of execution for serial queues.

Case 1



let serial = DispatchQueue(label: "first")

serial.sync {
    print("1")

    serial.sync {
        print("2")
    }

    print("3")
}


Enter fullscreen mode Exit fullscreen mode

Output: Error
Explanation: When we execute a block of code in serial queue with sync function the queue will be suspended till the block completes execution. Here in between we are trying to add new block with sync function will throw an error.
Error Screenshot

Case 2



let serial = DispatchQueue(label: "first")

serial.sync { // First block
    print("1")

    serial.async { // Second block
        print("2")
    }

    print("3")
}


Enter fullscreen mode Exit fullscreen mode

Output: 1 3 2
Explanation: The after executing the first block then it will take the second block which prints the number 2. The second block is async function so it will not crash.

Case 3



let serial = DispatchQueue(label: "first")

serial.async {
    print("1")

    serial.sync {
        print("2")
    }

    print("3")
}


Enter fullscreen mode Exit fullscreen mode

Output: 1
Explanation: The reason for this behaviour is a deadlock that occurs due to a circular dependency between the async and sync calls on the same serial queue.

Let's break down the execution step by step:

  • The async block is dispatched to the serial queue, and "1" is printed.
  • Inside the async block, there is a sync block dispatched to the same serial queue.
  • The sync block waits for the async block to complete before executing.
  • However, the async block cannot complete because it is waiting for the sync block to complete.

This creates a circular dependency, resulting in a deadlock, where both blocks are waiting for each other to finish.

Case 4



let serial = DispatchQueue(label: "first")

serial.async {
    print("1")

    serial.async {
        print("2")
    }

    print("3")
}


Enter fullscreen mode Exit fullscreen mode

Output: 1 3 2
Explanation: Using the async function will not suspend the serial queue from adding new blocks. The will complete execution on the order of inserting it. There will be an order for the code to execute.

Top comments (0)