What does main.sync in global().async mean?

x.sync means that the calling queue will pause and wait until the sync block finishes to continue. so in your example:

DispatchQueue.global().async {
    // yada yada something
    DispatchQueue.main.sync {
        // update UI
    }
    // this will happen only after 'update UI' has finished executing
}

Usually you don’t need to sync back to main, async is probably good enough and safer to avoid deadlocks. Unless it is a special case where you need to wait until something finishes on main before continuing with your async task.

As for A example crashing – calling sync and targeting current queue is a deadlock (calling queue waits for the sync block to finish, but it does not start because target queue (same) is busy waiting for the sync call to finish) and thats probably why the crash.

As for scheduling multiple blocks on main queue with async: they won’t be run in parallel – they will happen one after another.
Also don’t assume that queue == thread. Scheduling multiple blocks onto the same queue, might create as many threads as system allow. Just the main queue is special that it utilises Main thread.

Leave a Comment