DEV Community

Cover image for Is this code thread safe? Swift | iOS Development interview question
Bibin Jaimon
Bibin Jaimon

Posted on

Is this code thread safe? Swift | iOS Development interview question

Solution {
    static var names: [Int] = []
}
Enter fullscreen mode Exit fullscreen mode
  • The names variable is defined as a static property in the Solution class.
  • Static properties are shared among all instances of the class and can be accessed and modified from multiple threads concurrently.
  • Since there is no synchronization mechanism in place, concurrent access to the names array can lead to data races and inconsistent results.
  • If multiple threads attempt to modify the names array simultaneously, it can result in unexpected behaviour, such as incorrect or incomplete modifications, data corruption, or crashes.
  • To ensure thread safety, concurrent access to the names array should be synchronized using appropriate mechanisms like locks, serial queues, or other synchronization primitives.
  • Adding synchronization mechanisms will ensure that only one thread can access or modify the names array at a time, preventing data races and ensuring consistent behaviour.

Solution should be like below 🚀

class Solution {
    private static var names: [Int] = []
    private static let queue = DispatchQueue(label: "com.example.solution-queue")

    static func updateNames(_ name: Int) {
        queue.async {
            names.append(name)
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

🚀 LinkedIn
🚀 GitHub

Top comments (0)