DevPrep

All topics › Real interview tasks

A counter incremented 1000 times from multiple threads: fix it three ways

Middle PRO

Task

Why is the result below 1000, and how do you fix it?

var counter = 0
DispatchQueue.concurrentPerform(iterations: 1000) { _ in
    counter += 1
}
print(counter)   // 987? 994? — different every time

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store