Skip to content

Instantly share code, notes, and snippets.

@jeksys
Last active January 18, 2024 07:49
Show Gist options
  • Save jeksys/8dec2273e61ca18dd5b468960f504570 to your computer and use it in GitHub Desktop.
Save jeksys/8dec2273e61ca18dd5b468960f504570 to your computer and use it in GitHub Desktop.
Thread-Safe Arrays in Swift

What's concurrency

Concurrency means running more than one task at the same time.

What is a race condition?

When you have two threads changing a variable simultaneously. It’s possible to get unexpected results. Imagine a bank account where one thread is subtracting a value to the total and the other is adding a value.

What's thread safe in Swift

Nothing in Swift is intrinsically threadsafe Except: reference and static vars

Serial Queue Method

let queue = DispatchQueue(label: "MyArrayQueue")
queue.async() {
  // Manipulate the array here
}
queue.sync() {
  // Read array here
}

Concurrent Queue Method shared exclusion lock via barrier

let queue = DispatchQueue(label: "MyArrayQueue", attributes: .concurrent)
queue.async(flags: .barrier) {
  // Mutate array here
}
queue.sync() {
  // Read array here
}

Race condition test

var array = [Int]()
DispatchQueue.concurrentPerform(iterations: 1000) { index in
    let last = array.last ?? 0
    array.append(last + 1)
}

Swift uses a copy-to-write technique for value types as soon as it starts mutating it.

https://medium.com/@mohit.bhalla/thread-safety-in-ios-swift-7b75df1d2ba6

https://medium.com/swiftcairo/avoiding-race-conditions-in-swift-9ccef0ec0b26

https://gist.github.com/basememara/afaae5310a6a6b97bdcdbe4c2fdcd0c6

https://basememara.com/creating-thread-safe-arrays-in-swift/

https://xidazheng.com/2016/10/03/race-conditions-threads-processes-tasks-queues-in-ios/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment