Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Queue Priority seems not right

Tags:

ios

swift

so I am testing out some threading codes

private func queuesWithQos(){
    let queue1 = DispatchQueue(label: "com.appcoda.queue1", qos: .userInitiated)
    let queue2 = DispatchQueue(label: "com.appcoda.queue2", qos: .utility)

    queue1.async {
        print("Queue1 thread: \(Thread.current)")
        for i in 0..<10{
            print("Queue1:", i)
        }
    }

    queue2.async {
        print("Queue2 thread: \(Thread.current)")
        for i in 100..<110{
            print("Queue2", i)
        }
    }

    DispatchQueue.main.async {
        print("I am in main queue")
    }
}

And, I think that "I am in main queue" in this case should be printed first right since it is main thread and has the highest priority? But apparently, it is printed last?

I don't get it?

Can someone explain to me?

Thanks!

like image 996
progammingBeignner Avatar asked Mar 07 '26 22:03

progammingBeignner


1 Answers

The problem is not the small amount of work in the queues. In your case even if you increase the number of prints to whatever, chances are that the I am in main queue will never be called first.

If you run your code multiple times, you'll see that the I am in main queue shows at different states because the async command submits the job to a queue, it doesn't matter if it's main or background queue, it won't be executed now, it will take a few milliseconds depending on the load of the queue to be executed.

In your case, the "I am in main queue" job, takes just a few milliseconds to be scheduled for execution, but it's enough time for the other jobs to start executing their jobs (and maybe completing them). That's why you see the other logs first, it's that scheduling time delay.

Also you have to keep in mind that the main queue is in charge of UI display, so it might need more time to execute your job, if there is a rendering in process or other blocking operations.

If you want to have the "I am in main queue" executed first, simply remove it from the dispatch queue. That's something like saying "execute this NOW".

like image 51
danypata Avatar answered Mar 09 '26 14:03

danypata



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!