Daily iOS
Concurrency

Race conditions

This code gets called from several threads, and count comes out lower than expected. Can you explain why at the CPU level?

final class Stats {
    var count = 0
    func hit() { count += 1 }
}
How would an interviewer hear this answer? You'll see whether they'd move on, dig in, or say no, and which sentences would trip you up. Your score doesn't change.
See the short answer

count += 1 is a three-step read-modify-write (read, increment, write), so when two threads overlap one increment is lost. A concurrent write without synchronization is a data race, which is undefined behavior in Swift.

Share a question