Search code examples
swiftconcurrencygrand-central-dispatch

Do you have to manually specify that your DispatchQueue is serial?


I know that you can create a concurrent queue by doing the following:

let queue = DispatchQueue(label: "My Awesome Queue", attributes: .concurrent)

But I don't see an alternative enum for creating serial queues, something like:

let queue = DispatchQueue(label: "My Awesome Queue", attributes: .serial)

The only other possible option seems to be .initiallyInactive, am I missing something?

How do I specify in Swift that I want a serial queue?

Note that I am using the above queues like this:

queue.async {
    // do task 1
}

queue.async {
    // do task 2
}

// expect task 1 to start
// expect task 1 to finish
// expect task 2 to start
// expect task 2 to finish

Solution

  • let queue = DispatchQueue(label: "My Awesome Queue", attributes: .concurrent)

    When you use DispatchQueue with .concurrent attribute. It will execute in a concurrent manner.

    let queue = DispatchQueue(label: "My Awesome Queue")

    But if this attribute is not present, the queue schedules tasks serially in first-in, first-out (FIFO) order. Check the documentation here for more details.

    Btw : .initiallyInactive attribute is use to prevent the queue from scheduling blocks until you call its activate() method.