Swift Thread Safety

Karthik
2 min readJul 19, 2021

--

In this article, we gonna work with one of the GCD features (DispatchBarrier) to create a synchronization point.

In Swift world, almost nothing is thread-safe. we should make sure that the shared data is been read/write properly. the lock mechanism has the ability to create synchronization on the shared data. we got lots of options to create a lock kind of behavior.

  1. os_unfair_lock
  2. NSLock
  3. NSRecursiveLock
  4. DispatchSemaphore
  5. DispatchGroup
  6. DispatchBarrier (with concurrent queues)

Without talking much about the list, we gonna directly use DispatchBarrier which provides a great API to create synchronization.

DispatchBarrier

A dispatch barrier allows us to create a synchronization point within a concurrent dispatch queue. Normally, the queue acts just like a normal concurrent queue, When the barrier is executing, it acts as a serial queue that creates synchronization. Once the barrier finishes, the queue goes back to being a normal concurrent queue.

Now let's make an array thread-safe using dispatch barriers.

Implementation

In our project, we do have user availability which helps to know the user state. The state can be changed every second, in such cases we tend to get n number of incoming availability, in peak hours the N will be huge. so it's very important to protect the availability source from the race condition and concurrency issues. After so many iterations, we ended up choosing the DispatchBarrier to handle the synchronization.

TL;DR 🚀

Availability Model (Not exact one)
A synchronized cache that holds the availability state of each user

getAvailability offers concurrent reading since the dispatching queue is been marked as a concurrent queue. sync blocks the caller thread till the block execution completes. whereas on updateAvailability the dispatching queue is marked as async with barrier flag, which means that it will wait until every currently running block in the queue is finished executing before it executes. Other blocks will queue up behind it and be executed when the barrier dispatch is done.

Conclusion

custom serial queue is a bad choice for serialization, since barriers won’t do anything helpful since a serial queue executes one operation at a time anyway, custom concurrent queue is a great candidate for creating automaticity.

Hint: NSCache 😎 provide default synchronization since it's from Obj-C.

“Be the senior engineer you needed as a junior.” — Someone

Thank you for reading the post, leave a comment or a feature that you are using to create synchronization✌️.

--

--

Karthik
Karthik

No responses yet