ConcurrencyMidMCQ

What is a race condition and how do you prevent it?

Test your knowledge:

Explanation & Code

Answer: A race condition occurs when two or more threads access shared mutable state simultaneously, producing unpredictable results depending on timing.

Code Example:

// ❌ Race condition — counter could be corrupted
class UnsafeCounter {
    var count = 0
    func increment() { count += 1 }  // not thread-safe
}

// ✅ Option 1 — Use an actor (preferred in modern Swift)
actor SafeCounter {
    var count = 0
    func increment() { count += 1 }  // actor serializes access
}

// ✅ Option 2 — Serial dispatch queue
class QueueCounter {
    private var count = 0
    private let queue = DispatchQueue(label: "com.app.counter")

    func increment() {
        queue.async { self.count += 1 }
    }

    func value(completion: @escaping (Int) -> Void) {
        queue.async { completion(self.count) }
    }
}

Rate your understanding:

Ready to practice more Concurrency?

Test yourself with our interactive quiz mode or browse all curated questions for this topic.