Concurrency means running more than one task at the same time.
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.
Nothing in Swift is intrinsically threadsafe Except: reference and static vars
let queue = DispatchQueue(label: "MyArrayQueue")
queue.async() {
// Manipulate the array here
}
queue.sync() {
// Read array here
}
let queue = DispatchQueue(label: "MyArrayQueue", attributes: .concurrent)
queue.async(flags: .barrier) {
// Mutate array here
}
queue.sync() {
// Read array here
}
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/