PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, September 30, 2022

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

 September 30, 2022     concurrency, dispatch-queue, grand-central-dispatch, ios, swift     No comments   

Issue

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.



Answered By - udi
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing