Search code examples
iosswiftconcurrencygrand-central-dispatchdispatch-queue

Which one will execute first if we submit two tasks to same dispatchqueue?


Created Custom dispatch queue and submitted two tasks to same queue and I gave sleep(3) for first task and sleep(1) for second task. then why first task completes execution first?

let queue = DispatchQueue(label: "name");

queue.async {

    Thread.sleep(forTimeInterval: 3)

    print("Task1 done")
}

queue.async {

    Thread.sleep(forTimeInterval: 1)

    print("Task2 done")
}

Solution

  • In order for them to execute in a concurrent manner u have to use attributes: .concurrent as follows.

    let queue = DispatchQueue(label: "name", attributes: .concurrent);
    
    queue.async {
        
        Thread.sleep(forTimeInterval: 3)
        
        print("Task1 done")
    }
    
    queue.async {
        
        Thread.sleep(forTimeInterval: 1)
        
        print("Task2 done")
    }
    

    If you omit that part, the dispatch queue executes tasks serially. That is what you are experiencing.

    Check the documentation here.

    The attributes to associate with the queue. Include the concurrent attribute to create a dispatch queue that executes tasks concurrently. If you omit that attribute, the dispatch queue executes tasks serially.