How to create a serial DispatchQueue by setting its target to a concurrent queue?

Viewed 591

Because each dispatch queue consumes thread resources, creating additional concurrent dispatch queues exacerbates the thread consumption problem. Instead of creating private concurrent queues, submit tasks to one of the global concurrent dispatch queues. For serial tasks, set the target of your serial queue to one of the global concurrent queues. That way, you can maintain the serialized behavior of the queue while minimizing the number of separate queues creating threads.

https://developer.apple.com/documentation/dispatch/dispatchqueue

When the documentation says to create a serial DispatchQueue by setting the target of the queue to a global concurrent queue, is this what they mean?

let q = DispatchQueue(label: "someSerialQueue", qos: .default, attributes: [], autoreleaseFrequency: .inherit, target: .global())

Also, is this really preferred over simply labeling it:

let q = DispatchQueue(label: "someSerialQueue")
1 Answers

Although it's less convenient to use the first variant, it can prevent the proliferation of threads in your applications.

If you create a serial queue using the more verbose syntax, the tasks submitted to your serial queue will be executed on the threads assigned to the global queue. The system doesn't have to spawn new threads when the queue is created.

In the second case you don't set a target queue:

let q = DispatchQueue(label: "someSerialQueue")

Thus, the system will associate new threads with the newly created queue, increasing the thread consumption of your application.

So, the longer syntax brings huge benefits - definitely worth the small investment.

Related