Simple as the title states. Basically, in this example, could we ever get an invalid state:
var myBool = false
// Thread 1
while true {
if randomEvent() {
myBool = true
}
}
// Thread 2
while true {
if myBool {
print("Was set to true")
} else {
print("Not set")
}
}
Could this ever crash because myBool is in some invalid state? Or is this "safe"?
I'm not sure what you think this has to do with "thread-safe" or "atomic" or even Swift. The nature of multithreading is as follows. Whenever you say something of this form:
...you should assume that if
myBool
can be set on another thread, it can be set between the first line and the second. This could cause"Was set to true"
to be printed even though at this moment it isfalse
, or converse could cause it not to be printed even though at this moment it istrue
.After discussion on the Swift Users mailing list, it was confirmed that read and write of Bool values is not an atomic operation in Swift. Furthermore, the code above may be optimised by the compiler and since
myBool
is never set in the context of thread 2, it may optimise out the check. The only valid way to do this in Swift is to use GCD to marshall correctly, or use an OS provided locking feature.