Thursday, June 2, 2016

Creating a serial GCD queue with custom QoS priority

Did you know the system dispatch queues are defined as concurrent? That was an annoying bug on my side to fix. So, today's adventure: create our own, serial worker queue with a custom priority. Priority is defined in two stages: the QoS class (from highest to lowest: interactive, user initiated, utility, or background), and a scheduling priority relative to said class.

We have to specify the queue's behavior using a struct built by dispatch_queue_attr_make_with_qos_class, and what Apple's official docs as of today tell you about relative_priority won't even compile. Also, it's wrong, so I won't repeat it here.

Fortunately, there is a place with the correct information - usr/include/dispatch/queue.h:

 @param relative_priority
A relative priority within the QOS class. This value is a negative offset from the maximum supported scheduler priority for the given class.
Passing a value greater than zero or less than QOS_MIN_RELATIVE_PRIORITY results in NULL being returned.

So, to create a serial queue with maximum priority in the default class:

self.queue = dispatch_queue_create(
 "OHAI",
 dispatch_queue_attr_make_with_qos_class(
  DISPATCH_QUEUE_SERIAL,
  QOS_CLASS_DEFAULT,
  0
 )
);


whereas minimum priority would be:


self.queue = dispatch_queue_create(
 "OHAI",
 dispatch_queue_attr_make_with_qos_class(
  DISPATCH_QUEUE_SERIAL,
  QOS_CLASS_DEFAULT,
  QOS_MIN_RELATIVE_PRIORITY
 )
);


No comments:

Post a Comment