Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

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")
like image 342
kidcoder SAVE UKRAINE Avatar asked Aug 12 '26 15:08

kidcoder SAVE UKRAINE


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.

like image 88
Karoly Nyisztor Avatar answered Aug 14 '26 12:08

Karoly Nyisztor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!