DEV Community

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

Posted on

2

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

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series πŸ“Ί

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series πŸ‘€

Watch the Youtube series

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay