by saagarjha · 8y ago · 0 comments
This is addressed in the article, and a resolution is provided.
> It's even more confusing because some things are properly atomic (reference counts, manipulation of value types like arrays)
Modifying an array is not atomic, AFAIK. You cannot safely do this concurrently.
"Undefined state" is the language used in the article, and has no precise technical definition. The article suggests to me simply that a method might be called twice, and makes no mention of your bank account being emptied or demons flying out of your nose, which is the consequence of undefined behavior you should expect.
> Modifying an array is not atomic, AFAIK. You cannot safely do this concurrently.
I'm happy to correct errors (I'm not a Swift expert), but I'm going on the basis of copy-on-write semantics and the fact that `isUniquelyReferenced` seems to be implemented atomically - this is stated fairly clearly on the official Apple blog at https://developer.apple.com/swift/blog/?id=10 , but that might be out of date.
import Foundation
let q1 = DispatchQueue(label: "1")
let q2 = DispatchQueue(label: "2")
var a = [0]
q1.async {
a[0] = 1
}
q2.async {
a[0] = 2
}
You'll get an error at runtime that there's a data race.I believe this is pretty good evidence for my claim that understanding the thread safety is confusing.