Ios – Concurrent vs serial queues in GCD

concurrencygrand-central-dispatchiosmultithreading

I'm struggling to fully understand the concurrent and serial queues in GCD. I have some issues and hoping someone can answer me clearly and at the point.

  1. I'm reading that serial queues are created and used in order to execute tasks one after the other. However, what happens if:

    • I create a serial queue
    • I use dispatch_async (on the serial queue I just created) three times to dispatch three blocks A,B,C

    Will the three blocks be executed:

    • in order A,B,C because the queue is serial

      OR

    • concurrently (in the same time on parralel threads) because I used ASYNC dispatch
  2. I'm reading that I can use dispatch_sync on concurrent queues in order to execute blocks one after the other. In that case, WHY do serial queues even exist, since I can always use a concurrent queue where I can dispatch SYNCHRONOUSLY as many blocks as I want?

    Thanks for any good explanation!

Best Answer

A simple example: you have a block that takes a minute to execute. You add it to a queue from the main thread. Let's look at the four cases.

  • async - concurrent: the code runs on a background thread. Control returns immediately to the main thread (and UI). The block can't assume that it's the only block running on that queue
  • async - serial: the code runs on a background thread. Control returns immediately to the main thread. The block can assume that it's the only block running on that queue
  • sync - concurrent: the code runs on a background thread but the main thread waits for it to finish, blocking any updates to the UI. The block can't assume that it's the only block running on that queue (I could have added another block using async a few seconds previously)
  • sync - serial: the code runs on a background thread but the main thread waits for it to finish, blocking any updates to the UI. The block can assume that it's the only block running on that queue

Obviously you wouldn't use either of the last two for long running processes. You normally see it when you're trying to update the UI (always on the main thread) from something that may be running on another thread.

Related Topic