Search Your Question

What are different type of Queues in GCD?

Ans :

Queue : 

A Queue is a linear structure that follows the First In First Out (FIFO) order. Here we are going to use two types of queue Serial queue and Concurrent queue.

Serial Queue : 


Serial Queue

In the serial queue, only one task runs at a time. Once the first task ends then only the second task will begin. All the task follow the same sequence they have to wait until running task finish.

Create our own serial queue using GCD:


let serialQueue = DispatchQueue(label: "mySerialQueue")
 serialQueue.async {
  // Add your serial task

 }

Download images using serial queue : 


let myArray = [img1, img2, img3, img4, img5, img6]
   
   for i in 0 ..< myArray.count {
     serialQueue.async {
       do {
         let data = try Data(contentsOf: URL(string: myArray[i])!)
         if let image = UIImage(data: data) {
           DispatchQueue.main.async {
             self.imageSerial[i].image = image
           }
         }
       } catch {
         print("error is \(error.localizedDescription)")
       }
     }

   }


Concurrent Queue : 


Concurrent Queue

In the Concurrent queue, multiple tasks can run at the same time. The start time of the task will be the order they are added, means Task 0 start first then Task 1 will start after that and so on. Tasks can finish in any order.

Global queue is example of Concurrent queue.


// Synchronous
DispatchQueue.global().sync {
 // write your code here
}

// Asynchronous
DispatchQueue.global().async {
 // write your code here
}

Let's create own concurrent queue using GCD: 


let concurrentQueue = DispatchQueue(label: "myConcurrentQueue", qos: .default, attributes: .concurrent, autoreleaseFrequency: .inherit, target: nil)

 concurrentQueue.async {
  // Add your concurrent task
 }

Download images using concurrent queue:

let myArray = [img1, img2, img3, img4, img5, img6]

for i in 0 ..< myArray.count {
  concurrentQueue.async {
    do {
      let data = try Data(contentsOf: URL(string: myArray[i])!)
      if let image = UIImage(data: data) {
        DispatchQueue.main.async {
          self.imageConcurrent[i].image = image
        }
      }
    } catch {
      print("error is \(error.localizedDescription)")
    }
  }
}


No comments:

Post a Comment

Thanks