Dispatch Barrier in Swift

Arda Ersoy
2 min readJun 16, 2022

--

Photo by Andras Vas on Unsplash

What is a Barrier?

A dispatch barrier is a group of functions executing in a serial queue. It helps us synchronise executing one or more tasks in a dispatch queue. Use barriers when you need a queue to be delayed.

How to Use

Now let’s create a concurrent dispatch queue, and add async and sync tasks to it.

Add a sync task with a flag of .barrier to block other tasks. The tasks(sync, async) assigned before this block will be completed first. Then this task will execute and as it is a sync task no other task will start until it finishes.

Add another async code to the queue.

The output of the above block of code;

Conclusion

As you can see in the output, the execution of tasks 1 and 2 started. When we add a new task as a barrier, it stops the execution of others. After finishing the execution of task 3, then task 4 continues to execute.

References

--

--

Arda Ersoy
Arda Ersoy

Responses (2)