Swift 5.5 —Acquiring thread locks & sync made easy with Actor isolation

Berkin Tatlısu
2 min readJul 1, 2021

We will explore some new swift features which released in June2021, very simple and useful technics added to manage the thread props appweide.

What is a lock?

A lock is a tool for controlling access to a shared resource by multiple threads. Commonly, a lock provides exclusive access to a shared resource: only one thread at a time can acquire the lock and all access to the shared resource requires that the lock be acquired first. However, some locks may allow concurrent access to a shared resource, such as the read lock of a ReadWriteLock.
(from oracle docs. https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Lock.html)

One of the more difficult problems in developing concurrent programs is dealing with data races. Actors provide a model for building concurrent programs that are free of data races. They do so through data isolation: each actor protects is own instance data, ensuring that only a single thread will access that data at a given time. Actors shift the way of thinking about concurrency from raw threading to actors and put focus on actors “owning” their local state

“Which thread is the first to start isolated access?”

Swift guarantees that only code inside an actor can access the actor’s local state. This guarantee is known as actor isolation.

If BankAccount were a class, the transfer(amount:to:) method would be well-formed, but would be subject to data races in concurrent code without an external locking mechanism.

We create a racing condition on the actors, but now its thread safe due to actors nature.

Lets test it.

--

--