Member-only story
Preventing Data Races Using Actors in Swift
Say goodbye to data races
Data races — the worst nightmare of all developers! They are hard to detect, very unpredictable, and extremely difficult to fix. Apple has given developers various toolsets such as NSLock
and serial queues to prevent data races from happening during runtime, however, none of them are capable of catching race conditions during compile-time. With the release of Swift 5.5, this will no longer be the case!
Introducing Actor, the new Swift language feature that can help developers to catch any possible race conditions during development time. In this article, we will first look at how a data race occurs when using dispatch queues and asynchronous tasks. After that, we will look at how actors can help us to identify race conditions in our code and prevent them from happening once and for all!
Without wasting any more time, let’s get right into it.
How Does a Data Race Occur?
A data race occurs when two or more threads trying to access (read/write) the same memory location asynchronously at the same time. In the context of Swift, it usually happens when we try to modify an object’s state using a dispatch queue. What do I mean by that?
Consider the following Counter
class that has a count
variable where every time the addCount()
function is called, it will increase by 1:
Now, let’s say we have a button that will trigger the following code:
Basically, what the above code does is to call the Counter
‘s addCount()
function 1,000 times asynchronously using a dispatch group. Once the dispatch group execution is completed, we will show the counter
‘s count
value on a label.