What is the potential concurrency issue in the following Swift code snippet, and how can it be best addressed?

iOS interview question for Intermediate practice.

Answer

A data race can occur because updatePerson is not actor-isolated, allowing multiple threads to modify the person object simultaneously.

Explanation

The updatePerson function is a non-isolated, synchronous function that mutates the person object. If this function is called concurrently from multiple threads with the same Person instance, it will create a data race, as multiple threads might try to write to the age property simultaneously leading to corrupted data or a crash. To fix this, mutations should be performed in a protected context, such as within a method on an actor that holds the data, or by ensuring all modifications happen on a single, dedicated thread or actor.

Related Questions