Why inactive concurrent queue blocking the full function execution?

Viewed 55

Step 1: Declare a concurrent queue .initialInactive

Step 2: Call the function having a sync closure.

let concurrentQueue = DispatchQueue(label: "com.semaphore", attributes: [.concurrent, .initiallyInactive])
func call() {
    print("1")
    print("7")
    concurrentQueue.sync {
    }
    print("13")
}

Output: 1, 7

For the below execution

func call() {
    print("1")
    print("7")
    concurrentQueue.activate()
    concurrentQueue.sync {
    }
    print("13")
}

Output: 1, 7, 13

1 Answers

You called with with sync, so the call will wait until the block is scheduled and completes. The queue is inactive, so it cannot schedule blocks. Therefore, the block can't complete, and the sync can't return. Is there a different behavior you're expecting from sync?

This construct is useful if you want all the processes to wait for some condition before starting. For example, you might make an inactive queue that guards access to something that needs to initialize (logging-in for example, or reading configuration from disk). Once that has initialized, it can call .activate(), and all of these other processes will start. If the system is already initialized, the .sync {} call will return immediately.

Related