Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are setting and reading a Bool atomic operations in Swift?

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

like image 315
Dale Myers Avatar asked Sep 17 '25 03:09

Dale Myers


2 Answers

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:

if myBool {
    print("Was set to true")

...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 is false, or converse could cause it not to be printed even though at this moment it is true.

like image 97
matt Avatar answered Sep 21 '25 02:09

matt


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.

like image 43
Dale Myers Avatar answered Sep 21 '25 03:09

Dale Myers