Dispatch Barriers in Swift 3

Ömer Yalhı
1 min readDec 27, 2016

--

Dispatch barriers can be used to speed serial queues for read write operations.

Serial Queues
Tasks in serial queues execute one a time in first in first out format. Task1 has to finish for Task2 to start. Task2 has to finish for Task3 to start and so on.

Below code reads and writes to the dictionary. Because the read and write operations are serial, we don’t run in to Readers–writers problem.

Concurrent Queues
Tasks in concurrent queues execute in any order and can start simultaneously. Below code reads and writes to the dictionary concurrently. This is very fast compared to the above serial queue. However, because we may be reading while writing at the same time, we will run in to the readers-writers problem.

Concurrent Queue with Barrier

What if there was a way that you can ensure no writing occurs while reading and no reading occurs while writing using concurrency? Well, there is a way to this using Concurrent Queue with Barrier. If we take the concurrent code above, and insert a barrier to the write operation, we ensure that the writing will occur after all the reading in the queue is performed and that no reading occurs while writing.

Using concurrent queues with barriers helps us improve and speed up our code while eliminating the readers-writers problem, which is also important for singletons.

--

--

Ömer Yalhı

Web and Mobile Developer, Creator of the free app: Steps Leaderboard, w/ Live Step Counting:iTunes store link: https://itunes.apple.com/app/id131208