Sobes.tech
Junior — Middle

Millised mehhanismid tagavad turvalise töötamise asünkroonse koodiga ja ennetavad võistlusolukordi async/await kasutamisel?

sobes.tech AI

Vastus AI-lt

To work safely with asynchronous code and prevent race conditions when using async/await on iOS (Swift), the following mechanisms are used:

  • Serialization of access to shared resources: using queues (DispatchQueue) with barriers or serial queues for synchronization.
  • Actors: in Swift, actors ensure state isolation and sequential access to it, preventing race conditions.
  • Using Task and await with proper execution context management: to avoid concurrent access to the same data.

Example with actors:

actor Counter {
    private var value = 0

    func increment() {
        value += 1
    }

    func getValue() -> Int {
        return value
    }
}

let counter = Counter()
Task {
    await counter.increment()
    print(await counter.getValue())
}

Here, the actor guarantees that access to value will be sequential, preventing race conditions.