“This is the sixth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

The GCD introduction

What is the GCD

Grand Central Dispatch is an API for C

The GCD advantage

  • CGD is apple’s solution for multi-core parallel computing (starting with iOS4)
  • The GCD automatically uses more CPU cores
  • The GCD automatically manages the thread life cycle (create thread, schedule thread, destroy thread), and the programmer only needs to tell the GCD what task he wants to perform, without writing any thread management code

GCD tasks and queues (queue: the queueblock🙂

The GCD task

Task: Perform an action, that is, a piece of code that executes in a thread. In GCD it is placed in a block. There are two ways to execute a task: synchronous execution and asynchronous execution

  • Synchronous execution

    The system synchronously adds tasks to a specified queue. The system waits until the tasks in the queue are complete before executing other logic

    dispatch_sync(dispatch_queue_t  _Nonnull queue, <^(void)block>)
    Copy the code
  • Asynchronous execution

    Asynchronously adds a task to a specified queue. It does not wait for the task to finish. Once the task is added to the queue, it can continue to execute the following logic

    dispatch_async(dispatch_queue_t  _Nonnull queue, <^(void)block>)
    Copy the code
  • The difference between synchronous and asynchronous

    • Synchronization: Tasks can only be executed in the current thread without the ability to start new threads
    • Asynchrony: The ability to execute tasks in new threads, with the ability to start new threads

The GCD queues

Queue: A queue used to store tasks. A queue is a special linear table that uses FIFO (first in, first out), meaning that new tasks are always inserted at the end of the queue and read from the head of the queue. Each time a task is read, a task is released from the queue. The GCD has two types of queues: serial and concurrent

  • Concurrent queue: Multiple threads can be started and multiple tasks can be executed simultaneously. The concurrency function is only available with the asynchronous dispatch_async method

  • Serial queue: Only one thread is started and tasks are executed one after another

Note: there are four confusing concepts: synchronous, asynchronous, concurrent and serial

  • Synchronization and asynchrony mainly affect whether threads can be opened
  • Serialization and parallelism mainly affect how tasks are executed

The GCD use

  • Create a queue (serial queue or concurrent queue)
  • The task is appended to the task’s wait queue, and the system executes the task (synchronous or asynchronous) based on the task type