Sobes.tech
Junior

What is a Dispatch queue?

sobes.tech AI

Answer from AI

Dispatch Queue is a lightweight object that submits tasks for asynchronous or synchronous execution in GCD (Grand Central Dispatch).

Types of queues:

  1. Serial: Executes tasks strictly in order, one after another.
  2. Concurrent: Executes tasks simultaneously (as allowed by the system and available CPU cores).

Ways to obtain queues:

  • Main Queue: A serial queue associated with the main thread of the application (UI).
    let mainQueue = DispatchQueue.main
    
  • Global Concurrent Queues: Provided by the system with different quality of service (QoS) priorities.
    let userInitiatedQueue = DispatchQueue.global(qos: .userInitiated)
    
  • Custom Queues: Can be serial or concurrent.
    let customSerialQueue = DispatchQueue(label: "com.example.mySerialQueue")
    let customConcurrentQueue = DispatchQueue(label: "com.example.myConcurrentQueue", attributes: .concurrent)
    

Submitting tasks:

  • async: Adds a task to the queue for asynchronous execution, not blocking the current thread.
    customSerialQueue.async {
        // Asynchronous task
    }
    
  • sync: Adds a task to the queue for synchronous execution, blocking the current thread until the task completes.
    customSerialQueue.sync {
        // Synchronous task
    }
    
    Use sync with caution, especially on the main queue, to avoid deadlocks.

Applications:

  • Executing background tasks without blocking the UI.
  • Managing access to shared resources (serial queues are used for synchronization).
  • Parallelizing computations.