#09: Creating DispatchQueues in Swift 3

To create a new serial queue, a queue that will execute your closures sequentially, you just need to provide a label to identify it. It’s recommended to use a reverse order domain name prefix to make it easier to track back the owner of the queue in stack traces.

let serialQueue = DispatchQueue(label: "com.uraimo.Serial1")  //attributes: .serial

let concurrentQueue = DispatchQueue(label: "com.uraimo.Concurrent1", attributes: .concurrent)

The second queue is concurrent and that means that the queue will use all the available threads when executing the jobs it contains. Order of execution is unpredictable in this case, don’t assume that the completion order of your closures will be in any way related to the insertion order.

The default queues are easily accessible from the DispatchQueue object:

let mainQueue = DispatchQueue.main

let globalDefault = DispatchQueue.global()

The main queue is the sequential main queue that handles the main event loop for graphical application on either iOS or macOS, responding to events and updating the user interface. As we know, every alteration of the user interface should be performed on this queue.

To retrieve a specific default global queue, use the global(qos:) getter specifying the desired priority (from higher to lower): userInteractive, userInitiated, default, utility, background, unspecified.

let backgroundQueue = DispatchQueue.global(qos: .background)

The same priority specifier can be used with or without other attributes also when creating custom queue:

let serialQueueHighPriority = DispatchQueue(label: "com.uraimo.SerialH", qos: .userInteractive)

Now, let’s see a quick example of usage:

globalDefault.async {
    print("Async on MainQ!")

globalDefault.sync {
    print("Sync in MainQ!")

globalDefault.asyncAfter(deadline: .now() + .seconds(5)) {
    print("After 5 seconds")

Did you like this post? Let me know on Twitter or subscribe for updates!

This is the blog of Umberto Raimondi, you can reach me at me@this domain.

I'm also on Twitter and GitHub.

Subscribe via RSS or email.