Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> This is addressed in the article, and a resolution is provided.

"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.




Try compiling this with swiftc -sanitize=thread:

  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.


This is a subtle point. It's not the array assignment that's the race here, but the update to the shared (by closure capture) `a` variable. You'd get the same data race if `a` were an `Int`, and we don't say that integers are non-thread-safe. If each closure had its own reference to the array, it would be copied on write.

I believe this is pretty good evidence for my claim that understanding the thread safety is confusing.




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: