Dispatch barrier, does it block or delay others?

After watching the Introducing Concurrency Part 9: Thread-safe Resources video tutorial I got something that is it at the base that I need to understand.
At the tutorial, “Freddie Frost” is printed to the console by every thread.
So I said to myself that it seems that the first barrier that put in the queue or run, is blocking the others barriers, and prevent them to even be put on the queue.
In contrast the print of the name is not rejected, and they print the name.
Initially I thought that the other barriers will wait to their turn to run and will change the name serially.

@samdavies can you clarify?


When you add a dispatch_barrier to the queue, it will work its way up the queue in the same way as any other task. However, once it is ready to be executed, it waits for currently running tasks to be completed before beginning execution. It also prevents any future tasks in the queue from executing.

This has the effect of turning the concurrent queue into a serial queue for this one task. Once that task has completed, the queue continues operating as before.

The difficulty with demonstrating this is that concurrency is often non-deterministic. So the output you see on the screen won’t always be the same. Try rerunning the playground to see whether you can replicate the inconsistent state.

Hope that helps :slightly_smiling:


1 Like

When running couple of time, there is a different result, thats true.
But I thought that there will be 5 changing of a name, because we add 5 dispatch_barrier one after another, so it will very serial.
The first barrier will hold from executing the second one, the second will hold the three…
That is why I still confused.
Can you clarify this more?


The code you’re referring to is the following:

for name in nameList {
  dispatch_group_async(threadSafeNameGroup, workerQueue) {
    threadSafePerson.changeName(firstName: name.0, lastName: name.1)
    print("Current threadsafe name: \(threadSafePerson.name)")

The changeName() line causes a dispatch barrier to be added to the queue, whilst the threadSafePerson.name is performed serially - i.e. the calling thread will be held up until that can return.

Notice that these lines are called once for each name, and importantly these calls are dispatched asynchronously on a concurrent queue. In reality this means that the 5 dispatch barrier calls will be pushed onto the isolation queue, before any of the synchronous reads. Therefore you’ll get the non-deterministic behaviour that you’re seeing in the code.

Hope that explains it.


Ya! The “Notice…” paragraph did the trick for me. Now I understand. I really like this subject.
Thank you.
BTW, a superb series.
(A book like “Advanced concurrrency by tutorials” would be sweet. Just saying.)

1 Like