Search code examples
iosswiftios-multithreading

How does .enforceQoS flag increase priority?


I tried to increase the priority of the block executed in the concurrent queue. I suggested that the flag enforceQoS is suitable for this purpose. As Apple docs said:

This flag prioritizes the block's quality-of-service class over the one associated with the current execution context, as long as doing so does not lower the quality of service.

Suppose there is a queue:

/// Lowest priority queue
let concurrentQueue = DispatchQueue(label: "queue.conc.test", qos: .background, attributes: .concurrent)

We also have several DispatchWorkItem tasks, some of which are:

let item1 = DispatchWorkItem(qos: .userInitiated) { /* execute block */ }
let item2 = DispatchWorkItem(qos: .utility, flags: .enforceQoS) { /* execute block */ }

My question is simple: does Apple guarantee that item2 execute early?

I played in the playground a little bit and unfortunately didn't reveal any advantages of this flag, the results were absolutely chaotic. The official documentation also didn't help in this matter.

Thanks a lot.


Solution

  • "Prioritize" here doesn't mean "run sooner." It means "when deciding which QoS to assign for this block, prefer the one given here you rather than the one that the current execution context suggests (if the one given here is higher than what this block would otherwise receive)."

    If you require that item2 run before item1, then use notify to order them:

    item2.notify(queue: concurrentQueue, execute: item1)
    

    In no case should you try to use QoS to order work items. QoS is a complex system that includes more than just priority; it also includes things like whether the device is in an energy-saving mode. Assign items the QoS that matches their intent, based on the descriptions of each service level. If you require things to run in a certain order, then use dependencies (like notify) to order them.